Saturday, November 28, 2026

MERCURY AGENT v2.2.1 - A GUIDED TOUR OF A GOVERNED, SELF-EXTENDING AGENT RUNTIME




A note on how to read this article

The discussion that follows is based on the Mercury Agent software, specifically version v2.2.1, which is the most recent release available at the time of writing and can be found in the public repository located at https://github.com/ms1963/mercury_agent.



1. What Mercury Agent actually is

Mercury Agent takes a distinct approach, moving beyond the conventional notion of an AI agent as merely a chat interface that invokes a limited set of tools. Instead, it is designed as a compact operating system tailored for language-model work, featuring a centralized hub where every model call is carefully managed - admitted, authenticated, metered, and routed. This architecture also incorporates a capability system that determines the agent's permissions and access rights, as well as a versatile runtime environment that can be seamlessly embedded as a library, driven from the command line, or exposed as a web service complete with an administrative console. The Mercury project is built as a TypeScript monorepo, requiring Node.js version 22.5 or later, and is organized into seven interconnected packages that collectively form the system's framework, with the core package serving as the intelligence center, the tools and mcp packages providing the agent's functional capabilities, the runtime package integrating these components into a unified facade, the server package transforming this facade into an HTTP service with a browser-based UI, the gateway package enabling multi-user access, and the cli package offering the primary command-line interface for daily interaction.


To understand the relationships between these components before delving deeper, the following figure illustrates a single user turn from the outermost layer inward, providing a reference point that subsequent sections can draw upon for clarification.

user turn

  |

  v

cli / server / gateway            (entry surfaces)

  |

  v

Agent.run()                       (the reasoning loop, in @mercury/core)

  |

  v

LLMService.chat()                 (the single governed model gateway)

  |

  +--> ModelRouter               (pick a concrete provider/model)

  +--> PolicyEngine (RBAC)       (is this principal allowed this model?)

  +--> BudgetService             (can this call be afforded?)

  +--> ProviderRegistry          (OpenAI/Anthropic/Ollama/LM Studio/...)

  |

  v

provider call -> retries -> fallback chain -> usage ledger -> events

A key observation to make here is that the arrow emanating from the reasoning loop does not directly connect to a provider, instead it passes through LLMService, which serves as the narrow waist of the overall design, ensuring that all interactions with models are properly mediated, and nothing is able to call a model without going through this central service.



2. The single gateway, and why a narrow waist matters

The gateway's header comment succinctly summarizes its role as the sole entry point for all model calls, where it sequentially applies routing, role-based access control, budget pre-checks, and the actual provider call complete with retries, fallback chains, and text-mode adaptation for tool-less models, before ultimately logging usage and emitting events, and as the constructor reveals, this functionality is neatly decomposed into a set of specialized collaborators, each capable of being independently reasoned about and tested.

// packages/core/src/llm/service.ts (shape of the collaborators)

export class LLMService {

 constructor(

   private config: MercuryConfig,

   readonly registry: ProviderRegistry,  // knows every configured backend

   readonly router: ModelRouter,          // turns "auto" into a concrete id

   private budgets: BudgetService,        // affordability + usage ledger

   private policy: PolicyEngine,          // RBAC: may this principal do this?

   private bus: EventBus,                 // observable side-effects

   private hooks?: HookManager,           // user-supplied extension points

   private taskBudgets?: TaskBudgetService // optional hard per-task limits

 ) {}

}

Examining the constructor from top to bottom reveals a step-by-step description of the request lifecycle, where a call is received with a principal, a list of chat messages, and an optional model identifier, and if the caller does not specify a model or requests the string "auto" and a routing chain is configured, the service determines a concrete model by matching the request's tags against the criteria of each routing entry, subsequently passing this selection to the router for access-control filtering and fallback chain processing, allowing a cheap private request and an expensive hard request to be handled by different models without the calling code being aware of or concerned with which model responded, and the following listing is the exact passage that performs this criteria-based selection, demonstrating how it combines the caller's explicit tags with tags inferred from the task text.

// packages/core/src/llm/service.ts (criteria-based auto-selection)

let explicitModel = call.model;

if ((!explicitModel || explicitModel === 'auto') && this.config.llm.routing.length) {

 const requestTags = [...new Set([...(call.tags ?? []), ...inferTags(task)])];

 const picked = selectModelByCriteria(this.config, {

   tags: requestTags,

   needsVision: needs.vision,

 });

 if (picked) {

   explicitModel = picked;

   this.bus.emit({ type: 'llm.route', runId: call.runId,

     data: { model: picked, reason: 'criteria', criteria: requestTags } });

 }

}

Each model is assigned its own circuit breaker, which is created on demand the first time it is utilized, and only legitimate retryable failures, such as a rate-limit response, a server error, or a dropped connection, are counted against it, whereas a straightforward validation error will not trigger the breaker. The event bus publishes state transitions, allowing an operator to monitor a problematic provider as it opens and recovers in real time, rather than finding out about it later through a log. This marks the point at which Mercury's governed nature becomes tangible, as reliability emerges as an intrinsic property of the gateway, rather than a secondary consideration that must be retrofitted at each call site.



3. Remote models: configuration first, code second

Mercury interprets a layered configuration where built-in defaults are supplemented by a YAML file, then further refined by environment variables, and ultimately overridden by command-line flags, ensuring that the highest-priority source takes precedence. The configuration file is searched for in the working directory as ./mercury.yaml, or at the path specified by the MERCURY\_CONFIG variable, or at ~/.mercury/config.yaml, and its schema is designed to provide sensible defaults for every field, allowing an almost-empty file to still produce a functional system once a provider is defined. As a result, configuring a remote provider requires only a minimal amount of configuration, typically just a few lines. The following listing demonstrates how to integrate OpenRouter, an aggregator that provides access to dozens of hosted models through a single OpenAI-compatible endpoint, and intentionally omits the secret key from the file by referencing an environment variable instead of embedding the key directly.

# ~/.mercury/config.yaml  (a remote provider, key read from the environment)

llm:

 defaultModel: auto

 providers:

   openrouter:

     type: openrouter

     apiKeyEnv: OPENROUTER_API_KEY   # the key is NEVER written into the file

In practice, this approach proves comfortable to use because Mercury automatically enables a cloud provider as soon as it encounters the corresponding key in the environment, even in the absence of a providers block, due to the registry referencing a small table that associates each known provider type with its standard environment variable, and the following listing illustrates the relevant table and loop that processes it, which in turn explains why the straightforward approach of exporting the key and proceeding works seamlessly.

// packages/core/src/llm/registry.ts (keys that auto-enable a provider)

const ENV_KEYS: Record<string, string> = {

 openai: 'OPENAI_API_KEY',

 anthropic: 'ANTHROPIC_API_KEY',

 openrouter: 'OPENROUTER_API_KEY',

 chatllm: 'CHATLLM_API_KEY',

};

// ...in the registry constructor:

for (const [id, env] of Object.entries(ENV_KEYS)) {

 if (process.env[env] && !config.llm.providers[id]) {

   this.register(createProvider(id, { type: id, enabled: true },

     config.llm.timeoutMs, overridesFor(id)));

 }

}

At the core of all OpenAI-style providers lies a single implementation, whose header comment candidly reveals its extensive scope, supporting not only OpenAI itself, but also OpenRouter, LM Studio, Ollama's /v1 surface, vLLM, a llama.cpp server, and any other endpoint that communicates through the OpenAI Chat Completions dialect, and it is precisely this class that enables the transition from a remote model to a local one to be a matter of updating the address rather than rewriting the code, a topic that will be explored in greater detail in the following section.



4. Local models: the same dialect, a different address

In Mercury, a remote giant and a laptop-sized model can be used interchangeably because they are accessed through the same OpenAI-compatible provider, with the sole distinction being the base URL, and since the project includes default base URLs for typical scenarios, specifying the provider type is generally sufficient.

// packages/core/src/llm/providers/openai.ts (built-in base URLs)

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',   // LM Studio's local server

 ollama:     'http://localhost:11434/v1',  // Ollama's OpenAI surface

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

};

To deploy a local model, you simply need to declare it, and this can be achieved by extending the existing configuration, as illustrated by the fragment below, which makes an Ollama instance running on the same machine available under the identifier ollama/llama3.1, requiring no API key since a local server does not need one, and explicitly showing the baseUrl line, even though it matches the default, in order to highlight the possibility of using a different address.

# ~/.mercury/config.yaml  (adding a fully local provider)

llm:

 providers:

   openrouter:

     type: openrouter

     apiKeyEnv: OPENROUTER_API_KEY

   ollama:

     type: ollama

     baseUrl: http://localhost:11434/v1   # local, no key required

By leveraging this provider, you can develop a single program that efficiently allocates tasks between a private local model, which handles high-volume, straightforward work, and a remote frontier model, which is reserved for genuinely challenging tasks, all without explicitly referencing HTTP, keys, or retries in the code. This is achieved by booting the runtime as a library, obtaining an authenticated principal, and then making two distinct calls that primarily differ in the level of routing responsibility they delegate. The first call relies on the router and its associated routing chain to make the decision, while the second call explicitly specifies a remote model, justifying the additional expense due to the task's complexity, and the code that follows demonstrates how this is implemented.

// run-both.ts  -  one program, local for the easy turn, remote for the hard one

import { createMercury } from '@mercury/runtime';

async function main(): Promise<void> {

 // Boot from ~/.mercury/config.yaml. startServices:false keeps this a pure

 // library embedding: no HTTP server and no background schedulers are started.

 const mercury = await createMercury({ startServices: false });

 // Every model call is made on behalf of an authenticated principal so that

 // RBAC and budgets apply even in a tiny embedded script.

 const principal = await mercury.localPrincipal();

 // model:'auto' defers to the router + routing chain. The 'local' tag biases

 // the choice toward the private, near-zero-cost lane for a routine summary.

 const easy = await mercury.llm.chat({

   principal,

   model: 'auto',

   tags: ['general', 'local'],

   messages: [{ role: 'user', content: 'Summarise the CAP theorem in one sentence.' }],

 });

 console.log('[%s] %s', easy.modelId, easy.content);

 // A hard proof is explicitly pinned to a remote frontier model. The gateway

 // still applies RBAC, budgets, retries and the fallback chain underneath.

 const hard = await mercury.llm.chat({

   principal,

   model: 'openrouter/anthropic/claude-sonnet-4-5',

   tags: ['reasoning', 'code'],

   messages: [{ role: 'user', content: 'Prove that there is no largest prime number.' }],

 });

 console.log('[%s] %s', hard.modelId, hard.content);

 await mercury.shutdown();

}

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

 console.error(err);

 process.exit(1);

});

The key to this design is its symmetry, which allows for seamless flexibility. The result object encapsulates all the necessary information, including the content, the specific model identifier that generated the response, token usage, and cost, thereby enabling the caller to track which model handled each request without being tied to the underlying infrastructure. This symmetry also enables effortless swapping of the local backend, whether from Ollama to LM Studio or to a vLLM server hosted elsewhere, as this can be accomplished with a single line edit to the configuration, leaving the program itself entirely unchanged.



5. Lanes and cost-aware routing

Mercury elevates model interchangeability beyond a mere novelty by transforming the decision of where to run a model into a policy-driven process, achieved by assigning an economic lane to every model profile, with the schema defining three such lanes, as explained in the comment on the field in straightforward economic terms: the local lane, characterized by near-zero marginal cost, is suited for routine tasks on self-hosted hardware, the frontier lane is a premium option reserved for hosted models that require complex reasoning, and the default lane remains unclassified, allowing it to be used for any purpose, thereby ensuring that older configurations continue to function without modification.

// packages/core/src/config/schema.ts (the economic lane field)

lane: z.enum(['local', 'frontier', 'default']).default('default'),

By integrating with the criteria-based routing chain, an operator can define a concise, declarative policy that is remarkably readable, essentially stating: send general and local-tagged work to the local model, while directing reasoning and code work to the remote frontier model. The following listing expresses this policy precisely, and since the selected model still passes through access control and the fallback chain, the resulting policy functions as a preference, avoiding the rigidity of a hard-wired configuration.

# ~/.mercury/config.yaml (declarative routing by criteria)

llm:

 routing:

   - provider: ollama

     model: llama3.1

     criteria: [general, local]            # cheap, private, routine

   - provider: openrouter

     model: anthropic/claude-sonnet-4-5

     criteria: [reasoning, code]           # expensive, only when needed

The concept of an operating system framework proves particularly valuable in this context, as cost control is not an additional wrapper that developers must manually apply at each specific call site, but rather an inherent property of the runtime environment that is automatically inherited by every single call.



6. Fallback chains that degrade instead of failing

Hosted models can experience occasional downtime due to various issues such as overloaded frontier endpoints, quota limits being reached, or network disruptions. To address this, Mercury provides an opt-in, ordered fallback chain, which centralises the critical decision of determining whether a given error warrants a retry on an alternative model. This key decision is encapsulated in a single function, ensuring consistency across the system in defining the criteria for retrying, and the fallback chain itself is simply an ordered list of provider and model pairs that are attempted sequentially when the preceding one is unavailable.

# ~/.mercury/config.yaml (degrade from local to a cheap remote, in order)

llm:

 fallback:

   - provider: ollama

     model: llama3.1                  # try the private local model first

   - provider: openrouter

     model: openai/gpt-4o-mini        # if it is down, a cheap remote catches it

Management of the chain is accomplished from the command line using mercury fallback list, add, remove, and clear, while the routing chain offers corresponding mirror-image commands under mercury route, thereby allowing an operator to modify either policy without manually editing files. The combination of lanes, routing, and fallback yields a system that, through configuration alone, favors the cheapest acceptable model, automatically escalates to a more robust one when the workload demands it, and withstands an outage by redirecting traffic rather than presenting the user with an error.



7. Self-extending tools - the capability that is hardest to find elsewhere

The feature that most distinctly differentiates Mercury from other agent runtimes is its ability to recognize a missing capability and, under rigorous control, generate that capability on its own. This mechanism operates on an event-driven and cautious principle, where the runtime logs a "miss" for a particular capability when the agent attempts to access a non-existent tool, and only after the same capability has been missed a specified number of times, configurable by the user, does a synthesizer suggest a new tool. To ensure security, no newly created tool is automatically trusted. Instead, it is held for validation and approval, executed within a sandbox that imposes a time limit, and granted capabilities based on a deny-by-default policy, meaning that any draft requesting more privileges than allowed by the policy is simply rejected. The following listing is the actual configuration schema, and examining it provides the most straightforward way to understand the stringent security measures that are in place for this feature by default.

// packages/core/src/config/schema.ts (self-extension is off and sandboxed by default)

selfExtension: {

 enabled: false,            // the entire feature is opt-in

 missThreshold: 3,          // same capability must miss 3x before synthesis

 autoApprove: false,        // a human approves first-run by default

 allowFilesystem: false,    // deny-by-default capability grants

 allowNetwork: false,

 allowedHosts: [],          // a networked tool's hosts must be a subset of this

 allowShell: false,

 runtimes: ['python', 'node'],

 timeoutMs: 15000,          // per-tool wall-clock limit in the sandbox

 maxOutputChars: 20000,     // output handed back to the model is bounded

 // dir defaults to <dataDir>/synth-tools

}

The mechanism is integrated into the runtime as a fundamental component, rather than a plugin, and it actively listens on the event bus for the specific signal that triggers its operation, the following listing, taken from the runtime facade, demonstrates the synthesizer logging a miss when a named tool is not discovered, an event that serves as the catalyst for the potential creation of a future tool.

// packages/runtime/src/mercury.ts (a missing tool is recorded, not ignored)

if (name) this.synthesizer.recordMiss(name, '');

The end result is intentionally straightforward and transparent: each approved tool is saved as a standard folder on disk within the data directory's synth-tools path, eliminating the need for complex database migrations and allowing operators to easily read, review, or delete synthesized capabilities using a file browser. The approval and denial processes themselves are carefully controlled actions, made available as mercury addin commands and channeled through the same approvals layer that governs other sensitive operations. In essence, while many agent systems enable tool registration, Mercury Agent can, with explicit permission, generate tools, and it does so within a secure environment that features a sandbox, a miss-threshold, an approval gate, and a deny-by-default grant model, rather than relying on intuition or guesswork.



8. Hands-free voice, local or hosted, with graceful fallback

With the release of version 2.2.1, a seamless hands-free voice path is now available, adhering to the same local-or-remote philosophy that underlies the model layer, allowing for flexibility in deployment. In modern browsers, the client can leverage the built-in Web Speech API, but to accommodate Firefox and older Safari, which lack this API, the server offers a fallback capability to perform speech-to-text and text-to-speech functions internally. Notably, both the listening and speaking components can be configured to utilize either a hosted OpenAI-compatible endpoint or a self-hosted open-source server, thereby enabling privacy-conscious deployments to maintain audio processing on their own infrastructure. The configuration comments provide a detailed enumeration of the supported back ends, and the following listing demonstrates how to select a local whisper binary for transcription purposes and a local piper binary for synthesis.

# ~/.mercury/config.yaml (fully local voice: whisper in, piper out)

voice:

 stt:

   provider: whisper            # a local CLI; 'openai'/'openai-compatible'

   command: whisper             #   would instead call /audio/transcriptions

 tts:

   provider: piper              # a local CLI; point baseUrl at a self-hosted

   voice: en_US-amy-medium      #   server for the OpenAI-compatible path

By utilizing the same block with the provider set to openai-compatible and a baseUrl that references a self-hosted speech server, such as a faster-whisper service for listening or a Kokoro-style service for speaking, it is possible to maintain an open-source approach while leveraging the more robust OpenAI wire format, thereby illustrating a key design principle: the agent's interface remains stable, and swapping a local engine for a hosted one is simply a matter of configuration.



9. Security as a standing posture, not a toggle

At the heart of Mercury's security model lies the principle of least privilege, with a capability and credential broker serving as its cornerstone, deliberately designed to prevent the agent from holding onto standing keys, thereby ensuring that sensitive actions can only be performed by presenting a scoped and time-limited grant, specifically issued for a particular task and automatically expiring after a set period, and in the absence of such a grant, the action is categorically denied, with the schema explicitly defining the defaults, including the enabling of grants, a default grant lifetime of five minutes, and a strict one-hour limit on the maximum lifetime that can be requested.

// packages/core/src/config/schema.ts (the grant broker, on by default)

grants: {

 enabled: true,

 defaultTtlMs: 300000,     // 5 minutes

 maxTtlMs: 3600000,        // 1 hour hard ceiling on any requested TTL

}

To further bolster security, secrets can be kept out of plaintext entirely, as configuration values can contain references to external store keys, which are only resolved to actual values as needed, using a pluggable backend mechanism. This mechanism always has an environment backend available, and can also be extended to support Bitwarden and 1Password backends, allowing the agent to leverage their respective command-line tools. By combining expiring grants, deny-by-default tool capabilities, and just-in-time secret resolution, the agent becomes highly resilient, even in the event of a compromise, since it retains very little sensitive information that could be exploited.



10. Download, build, configure, deploy, and run

Setting up Mercury on a machine is intentionally straightforward, a deliberate design choice that will resonate with software engineers who have grown weary of specialized installation processes. To get started, you simply clone the repository, install the necessary workspace dependencies, and then build the TypeScript project references into executable JavaScript files. The following listing outlines the standard procedure, which presupposes that Node.js version 22.5 or later is already installed on your system.

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

cd mercury

npm install          # installs all seven workspace packages

npm run build        # tsc project references -> packages/*/dist

Once the build is established, an interactive wizard guides the user through the first-run setup process, which encompasses creating the administrative user and configuring an initial LLM provider, and subsequently, an environment check is performed to verify that the surrounding system is functioning correctly, at which point running the wizard followed by the doctor is the suggested initial step to ensure a smooth introduction to the system.

node packages/cli/dist/bin.js setup     # admin user + first LLM provider

node packages/cli/dist/bin.js doctor    # verify the environment

In your daily workflow, typing out the full path can be cumbersome, which is why the repository provides an npm script called mercury that essentially serves as a shortcut to the binary, and many users opt to create an alias for it. The two primary commands you will likely use frequently are initiating a direct chat from the terminal and accessing the web service, with the latter defaulting to providing both a browser-based UI and an HTTP API on port 3000.

npm run mercury -- chat        # a conversation straight from the terminal

npm run mercury -- serve       # web UI + API on http://localhost:3000

When deploying the service in a production environment, it is essential to ensure the serve process remains active across system restarts, a task typically handled by a process supervisor like systemd on Linux hosts. Additionally, a reverse proxy is typically positioned in front of the service to handle TLS termination and route a hostname to the local port, a common setup that Mercury seamlessly integrates with, as it is designed to be a well-behaved long-running Node service. As a result, the operational playbook for managing Mercury deployments aligns with the standard practices already in use on your platform. At startup, Mercury reads its configuration from the ~/.mercury/config.yaml file, previously discussed in this article, which conveniently encapsulates the entire behavior of a deployment, including model responses, voice localization, and grant lifetimes, into a single reviewable file, with sensitive secrets stored securely outside of it.


The command line offers a far more extensive range of capabilities than the basics initially imply, as the binary directs input to a wide array of subcommands, providing access to a broad spectrum of functionalities, including but not limited to managing models, the fallback chain, and the routing chain, as well as working with tools, skills, add-ins, and bundles, and handling memory, scheduling, and the self-maintaining wiki, in addition to teams, a mixture-of-agents mode, permissions, users, tokens, and audit, and also backup, restore, import, and update, among others, with the overall structure organised around the principle that each noun has its own associated verbs, which in turn helps to make discovery of these features a manageable process.



11. How this differs from the usual agent runtime

A natural question arises as to what sets Mercury apart from other agentic systems like Hermes Agent or OpenClaw, and the answer lies in its architectural design choices. Rather than comparing code from other projects, Mercury's distinct features can be understood through its own design, which funnels every model call through a single governed gateway, making routing, access control, budgets, retries, and fallback properties of the runtime rather than repetitive tasks at each call site. By treating local and remote models as peers behind a single OpenAI-compatible provider, Mercury allows private and hosted frontier models to be used interchangeably through configuration, and even mixed within a single task based on economic considerations. Additionally, under strict governance, Mercury can synthesize new tools when it lacks a capability, storing them in auditable on-disk folders behind a sandbox and approval gate. Furthermore, Mercury adopts a least-privilege security posture, where the agent holds no standing credentials, instead relying on short-lived, scoped grants and just-in-time secret resolution, making these four features unusual as default-on, first-class properties of a coherent runtime, which will be illustrated in the following listing.


To make a meaningful comparison with a specific competitor, it is advisable to review the source code of both systems simultaneously, a task made feasible by the open availability of Mercury's source code at https://github.com/ms1963/mercury\_agent, thereby allowing for a thorough examination in a relatively short period, rather than relying solely on marketing claims.



12. Where to go next

To gain a deep understanding of the Mercury Agent software, start by cloning the repository and running the setup wizard with a local Ollama model, which ensures that all data remains on your machine. Next, add a remote provider and a simple two-line routing policy, allowing you to observe the gateway as it alternates between them. This hands-on approach is invaluable, and taking it a step further by enabling self-extension in a scratch data directory will give you a tangible sense of the runtime's unique characteristics, as you witness a missing capability evolve into a fully approved and sandboxed tool. The entire process is detailed in the v2.2.1 source.

HOW LARGE LANGUAGE MODELS ARE TRANSFORMING CODE DEVELOPMENT



Introduction: A Paradigm Shift in Programming


The landscape of software engineering is experiencing a transformation unprecedented in its history. Large Language Models, the same technology that powers conversational AI systems, have emerged as powerful tools that fundamentally alter how developers write, test, debug, and maintain code. This is not merely about automating repetitive tasks or providing code completion suggestions. Rather, LLMs represent a fundamental shift in the relationship between human developers and the software development lifecycle itself.


These AI systems, trained on billions of lines of code from open-source repositories and technical documentation, possess an understanding of programming languages that extends far beyond simple pattern matching. They comprehend the semantic meaning of code, recognize design patterns, understand cross-language similarities, and can reason about program behavior in ways that traditional static analysis tools cannot. The implications of this capability are profound, touching every aspect of software engineering from initial code generation to long-term maintenance of legacy systems.


Code Generation: From Natural Language to Running Software


The most visible application of LLMs in software engineering is their ability to generate code from natural language descriptions. This capability has moved far beyond simple autocomplete features. According to research from GitHub, their Copilot system now produces up to forty-six percent of code in active repositories and makes developers fifty-five percent faster on routine tasks. These are not marginal improvements but represent a fundamental acceleration of the development process.


Modern code-focused LLMs such as OpenAI’s Codex, which powers GitHub Copilot, Meta’s Code Llama, Alibaba’s Qwen models, and Anthropic’s Claude have been specifically trained on massive corpora of code from multiple programming languages. For instance, Qwen models were trained on three trillion tokens of code-related data and support ninety-two programming languages including Python, C++, Java, PHP, C#, and JavaScript. These models can handle not just popular languages but also more specialized ones like COBOL, FORTRAN, and Haskell, making them valuable across the entire spectrum of software development.


The effectiveness of these models is measured through standardized benchmarks. HumanEval, developed by OpenAI, includes one hundred sixty-four programming challenges with corresponding unit tests. These challenges cover domains ranging from algorithms to Python language features, and critically, they were manually written to ensure they do not appear in training datasets. Models like Phind achieve up to eighty-two point three percent pass rate on HumanEval, demonstrating that LLMs can reliably solve programming problems without explicit training on those specific problems.


What makes LLM-based code generation particularly powerful is the context-awareness it brings. Unlike simple template-based generators, LLMs read filenames, neighboring functions, commit messages, and documentation strings. This contextual understanding allows them to generate code that aligns with domain vocabulary, architectural conventions, and project-specific patterns. A developer working on a financial application will receive suggestions that incorporate financial domain concepts, while a developer working on graphics code will see suggestions appropriate to that domain.


The real-world impact extends beyond individual productivity. Organizations report that LLM-assisted development reduces the activation energy required to tackle new projects. Tasks that developers might have indefinitely postponed due to the initial effort required now become feasible. This democratization of coding capability means that projects that would have languished in backlogs are now being completed, and developers with less experience can produce functional code with guidance from AI systems.


Automated Testing: From Manual Drudgery to Intelligent Test Generation


Software testing has long been recognized as critical to quality assurance but remains one of the most labor-intensive and often neglected aspects of software development. LLMs are transforming this landscape through automated test generation capabilities that go far beyond what traditional rule-based systems could achieve.


Meta’s TestGen-LLM represents a significant breakthrough in this area. During internal test-a-thons at Meta, the system successfully improved eleven point five percent of all classes to which it was applied. Seventy-three percent of its recommendations were accepted for production deployment by Meta software engineers. The system generates tests that meet strict criteria: they must build correctly, pass reliably, and increase code coverage. Seventy-five percent of TestGen-LLM’s test cases built correctly, fifty-seven percent passed reliably, and twenty-five percent increased coverage.


The approach combines LLM capabilities with rigorous validation. TestGen-LLM analyzes existing test suites, identifies gaps in coverage, and generates targeted tests that address those gaps. The system understands common testing patterns, can identify edge cases that human developers might miss, and generates tests that are not just syntactically correct but semantically meaningful. This means the tests actually validate important behavior rather than simply exercising code paths for the sake of coverage metrics.


IBM’s ASTER system demonstrates another approach to LLM-powered testing. ASTER uses lightweight program analysis to guide LLM prompting, generating unit tests that are both syntactically correct and semantically rich. The system incorporates software mocking mechanisms, enabling it to handle complex scenarios involving external dependencies such as database interactions or web service calls. This addresses a persistent challenge in automated testing where dependencies on external systems make it difficult to create isolated, repeatable tests.


The naturalness of LLM-generated tests represents a significant advantage. Previous automated test generation tools produced tests that developers found difficult to read and maintain. LLMs generate tests with meaningful variable names, clear assertion statements, and structure that follows human conventions. This naturalness makes the tests more likely to be accepted and maintained by development teams, addressing a long-standing obstacle to adoption of automated testing tools.


Meta’s Automated Compliance Hardening tool demonstrates how LLMs can be applied to mutation-guided test generation. The system generates realistic mutants representing actual concerns and automatically creates tests guaranteed to catch those faults. An engineer describes the kinds of bugs they are concerned about in plain text, and ACH generates mutations and tests to catch them. This approach significantly modernizes automated test generation and helps convert concerns from various sources into actionable test cases.


Program Repair and Debugging: AI as Your Debugging Partner


Debugging consumes a substantial portion of developer time, often requiring tedious investigation of error messages, stack traces, and code behavior. LLMs are emerging as powerful debugging assistants that can understand error messages, reason about program behavior, and suggest fixes.


The concept of self-debugging represents a particularly interesting development. Research has shown that LLMs can be taught to debug their own generated programs through a technique inspired by rubber duck debugging. Without any human feedback on code correctness or error messages, the model identifies its mistakes by executing the code and explaining it in natural language. On the Spider benchmark for text-to-SQL generation, self-debugging consistently improves baseline performance by two to three percent, with improvements of nine percent on the hardest problems. On benchmarks with unit tests like TransCoder and MBPP, self-debugging improves accuracy by up to twelve percent.


Modern approaches to automated program repair leverage LLMs in sophisticated ways. The DEVLoRe framework mimics how human developers fix bugs by using issue content, stack error traces, and debugging information. LLMs first localize buggy methods, then identify specific buggy lines and generate valid patches. Using the Defects4J dataset, DEVLoRe successfully localizes forty-nine point three percent of single-method bugs and generates fifty-six percent plausible patches. This demonstrates that different types of software artifacts complement each other in addressing various bugs.


InspectCoder introduces an innovative approach that enables LLMs to perform dynamic analysis through flexible debugger interaction. By initiating an interactive Python session within paused execution context, the system tests runtime code changes without modifying source files. This represents a critical advantage over existing methods that require error-prone file editing and costly re-execution. The system enables temporal, reversible perturbations of intermediate program states, providing immediate feedback for early adjustment of root cause understanding.


The practical impact of these debugging capabilities varies across LLMs. Testing of ChatGPT, Claude, Gemini, Deepseek, and LLaMA across real-world debugging tasks reveals distinct strengths. ChatGPT combines speed, clarity, and adaptability with precise bug detection and effective fixes. Claude and Gemini demonstrate structured thinking and software design sensibility, suggesting improvements aligned with best practices like encapsulation and validation. Deepseek and LLaMA perform well on complex logic and detailed error handling. The availability of multiple specialized models allows developers to choose tools suited to their specific debugging needs.


Documentation Generation: Making Code Comprehensible


Documentation is universally recognized as important yet frequently neglected due to time constraints and the tedious nature of writing comments and documentation. LLMs offer a solution by automatically generating high-quality documentation from code.


Several specialized tools have emerged in this space. Doc-comments-ai generates documentation comment blocks for all methods in a file, supporting both cloud-based models like GPT-3.5 and local LLMs without data leaks. The system is built with langchain, treesitter, llama.cpp, and ollama, providing flexibility in deployment options. LLMDocGen takes a broader approach, documenting not just Python files but also JavaScript, Java, C++ and other languages, functioning both as a library and command-line tool.


Research into LLM-generated documentation reveals both capabilities and limitations. Studies examining MUMPS and IBM mainframe Assembly Language Code found that LLM-generated comments are generally hallucination-free, complete, readable, and useful compared to ground-truth comments. However, assembly language poses particular challenges due to its low-level nature. A novel prompting strategy addresses the problem of incomplete comment generation and undesired code modification that plagued earlier approaches.


The evaluation of documentation quality represents an important research area. A scoring rubric measuring completeness, readability, usefulness, and hallucination provides a framework for assessing LLM-generated documentation. Research explores whether automated metrics such as code complexity measures and reference-based metrics like BLEU and ROUGE correlate with human evaluation of documentation quality. This work aims to provide organizations with frameworks to determine whether a given model performs well enough on their specific codebases to provide value through automation.


Context-aware documentation represents a particular strength of LLMs. The systems create dependency graphs of codebases, retrieve existing documentation from imported libraries, and generate comments that reference relevant documentation. This context awareness means that generated documentation does not exist in isolation but connects to the broader ecosystem of libraries and frameworks used by the code.


For function-level documentation, LLMs generate descriptions of function purpose, parameter types and purposes, return value explanations, and documentation of exceptions or errors. For inline comments, they provide explanations of complex code blocks, non-obvious algorithmic decisions, workarounds or technical debt notes, and statement of assumptions. This multi-level approach ensures comprehensive documentation coverage.


Legacy Code Modernization: Breathing New Life into Old Systems


Legacy systems represent both a critical business asset and a significant technical challenge. These systems, often written in languages like COBOL, MUMPS, or mainframe assembly, continue to run mission-critical applications in banking, insurance, healthcare, and government. Yet they pose challenges in efficiency, maintenance, staffing, and security. LLMs offer promise for modernizing these systems, though the task presents unique difficulties.


The challenge of legacy code modernization extends beyond simple translation. Legacy codebases often lack accurate documentation, contain hidden dependencies, and embody business logic through implicit assumptions rather than explicit specifications. Side effects that are not obvious from code inspection can mean that seemingly safe refactorings introduce subtle bugs that only surface under production conditions. These factors create technical debt that compounds over time.


LLMs approach legacy modernization through multiple capabilities. Code understanding and documentation generation address the critical problem of knowledge gaps. Many legacy systems suffer from lack of current documentation, making onboarding and refactoring extremely difficult. LLMs analyze these codebases and generate human-readable summaries, inline comments, and architectural overviews. This bridges the gap between tribal knowledge held by a few experienced developers and maintainable documented systems.


Automated code translation represents another key capability. Unlike traditional transpilers that perform one-to-one syntax mapping, LLMs understand business intent and design patterns embedded in code. They can rewrite applications from legacy languages like COBOL, Perl, or Visual Basic to modern equivalents like Python, Java, or TypeScript while also restructuring the output to follow modular, maintainable architectures aligned with modern software engineering principles.


Real-world experience reveals both successes and limitations. Organizations report fifty percent faster rebuild times when using LLM-assisted refactoring for legacy applications. Test coverage has been increased from twenty-two percent to over eighty percent through LLM-generated test cases. The resulting codebases are cleaner and more readable, with easier onboarding for new developers and greater confidence in deployments.


However, LLMs face significant challenges with legacy code. The tendency to hallucinate becomes particularly problematic when dealing with undocumented code or ambiguous logic. LLMs generate probabilistically likely outputs rather than guaranteed correct translations. The models may guess at appropriate behavior rather than recognizing lack of clarity. This issue is especially severe for code controlling mission-critical systems in aviation, medical devices, or financial trading where a single regression could endanger lives or cause massive financial loss.


The solution lies in hybrid approaches that combine LLM capabilities with solid engineering discipline. Organizations are advised to begin with low-risk modules, use LLMs to map dependencies and suggest refactors, then run new code through comprehensive test suites and code review processes. Each successful increment builds confidence and accelerates velocity. The key insight is that LLMs serve as powerful collaborators rather than replacements for thoughtful engineering.


The Tooling Ecosystem: Integrated Development Environments and Beyond


The practical application of LLMs in software engineering occurs through an expanding ecosystem of tools integrated into developer workflows. These tools range from IDE plugins to standalone applications, each addressing specific aspects of the development lifecycle.


GitHub Copilot represents the most widely adopted LLM-based coding assistant. Built on OpenAI’s Codex, it provides real-time code suggestions as developers type. The system has evolved significantly since its initial release, now handling more complex patterns and better understanding project context. Organizations report that Copilot-assisted developers complete tasks faster and with less cognitive overhead, allowing them to focus on higher-level design decisions.


Cursor and Windsurf demonstrate the next generation of AI-assisted development environments. These tools go beyond simple autocomplete to provide agentic capabilities. Windsurf reports that approximately ninety-five percent of their own code is written using their Cascade agent and passive coding features. This self-hosting demonstrates confidence in the capabilities and reveals how AI-assisted development is becoming the norm rather than the exception.


Amazon Q represents another approach, particularly optimized for AWS-related tasks and trained on Amazon’s internal codebase. Initial limitations have been addressed through integration of more capable models, making it valuable for developers working within the AWS ecosystem. Google’s Gemini integration into their development tools provides similar capabilities for Google Cloud customers.


Claude Code, launched by Anthropic, focuses on command-line agentic coding. The tool enables developers to delegate coding tasks directly from their terminal, integrating AI assistance into existing workflows. Internal reports suggest productivity increases ranging from two times to ten times depending on the developer and task.


These tools share common characteristics: they provide context-aware suggestions, support multiple programming languages, integrate with version control systems, and offer mechanisms for developers to accept, reject, or modify suggestions. The competition among providers drives rapid innovation, with each release bringing improvements in accuracy, speed, and capability.


Benchmarks and Evaluation: Measuring Progress


The rapid advancement of LLMs for software engineering necessitates robust benchmarking frameworks to measure progress and compare capabilities. Several benchmarks have emerged as standards for evaluation.


HumanEval remains foundational, focusing on whether code actually works as intended rather than simple text similarity. The benchmark uses pass-at-one evaluation, meaning the LLM has only a single chance to solve each challenge. This strict criterion separates models that genuinely understand programming from those that merely memorize patterns. Extensions include HumanEval-X covering Python, C++, Java, JavaScript, and Go, and HumanEval-XL with eighty problems across twenty-three natural languages and twelve programming languages.


EvalPlus offers eighty times the number of tests compared to original HumanEval, providing more comprehensive evaluation. SWE-bench evaluates models on real-world software engineering tasks, including multi-file changes and repository-level understanding. The benchmark uses actual GitHub issues and pull requests, testing whether models can understand requirements, locate relevant code, and implement fixes that pass test suites.


DevQualityEval focuses specifically on code quality aspects beyond mere functionality. The framework measures whether generated code follows best practices, handles edge cases properly, includes appropriate error handling, and maintains readability. This holistic evaluation approach recognizes that production code must meet standards beyond simply producing correct output.


MBPP, the Mostly Basic Python Problems benchmark, provides another evaluation dimension with problems of varying difficulty. The benchmark includes problems requiring understanding of language features, algorithms, and data structures. Model performance on MBPP correlates with ability to handle real-world programming tasks.


These benchmarks reveal interesting patterns. Larger models generally achieve better performance, demonstrating a scaling effect where additional parameters translate to improved capabilities. However, model architecture also matters. Infilling-style models that predict missing code given surrounding context often outperform generative models that predict code sequentially. This suggests that bidirectional context improves code understanding.


Challenges and Limitations: Tempering Expectations


Despite impressive capabilities, LLMs for software engineering face significant limitations that developers must understand to use them effectively.


Hallucination remains a persistent problem. LLMs generate probabilistically likely outputs, which means they can confidently produce code that appears correct but contains subtle bugs. This issue becomes critical in domains where correctness is paramount. Security vulnerabilities represent a particular concern, as studies show that code generated by AI assistants may introduce more security issues than manually written code.


Context window limitations constrain the complexity of problems LLMs can address. While modern models support increasingly large context windows measuring thousands or tens of thousands of tokens, this still falls short of repository-scale understanding. A large codebase may contain millions of lines of code with complex dependencies spanning multiple files and modules. LLMs struggle to maintain coherent understanding across such scale.


The correctness problem extends beyond functional accuracy to semantic correctness. Tests may pass while the code fails to implement the intended business logic. LLMs excel at generating code that satisfies stated requirements but may miss unstated assumptions or domain-specific constraints. This means human review remains essential, particularly for critical systems.


Cost represents another practical limitation. Using powerful commercial models for large-scale code generation, testing, or documentation can incur substantial expenses. Organizations must balance the productivity gains against API costs, particularly when processing large repositories or generating extensive test suites.


The training data bias issue affects LLM behavior in subtle ways. Models trained predominantly on open-source code may generate solutions appropriate for open-source contexts but ill-suited for enterprise requirements around security, compliance, or proprietary standards. Similarly, bias toward popular programming languages means less common languages receive less capable assistance.


Future Directions: The Evolving Landscape


The field of LLMs for software engineering continues to evolve rapidly, with several promising directions emerging.


Specialized domain models represent one trend. Rather than relying on general-purpose LLMs, organizations are creating domain-specific models trained on proprietary codebases and documentation. This approach addresses privacy concerns by keeping sensitive code internal while improving accuracy on domain-specific patterns and conventions. FinGPT exemplifies this approach for financial applications.


Multi-agent systems demonstrate potential for handling complex software engineering tasks. Rather than relying on a single LLM, these systems employ multiple specialized agents that collaborate. One agent might focus on code generation, another on testing, another on documentation, and another on architecture. This division of labor mirrors how human development teams operate and may prove more effective than monolithic approaches.


Retrieval-augmented generation addresses context window limitations by selectively retrieving relevant code snippets, documentation, and examples rather than attempting to process entire codebases. This approach combines the pattern recognition capabilities of LLMs with targeted information retrieval, potentially enabling repository-scale understanding.


Formal verification integration represents an exciting frontier. Combining LLMs with formal methods could enable generation of provably correct code. Systems like those working with Dafny demonstrate this approach, using formal specifications to guide LLM-generated repairs. This combination leverages the natural language understanding of LLMs with the guarantees provided by formal verification.


Tool-calling and agentic workflows enable LLMs to interact with development infrastructure. Rather than simply generating code, these systems execute tests, query databases, call APIs, and perform other actions. This capability transforms LLMs from passive code generators to active participants in the development process.


The Model Context Protocol introduced by Anthropic provides standardization for how LLMs interact with development tools. This protocol defines common interfaces for accessing code repositories, documentation, testing frameworks, and other development resources. Standardization accelerates ecosystem development and improves interoperability.


Conclusion: A New Era of Software Development


The integration of Large Language Models into software engineering represents more than incremental improvement in developer productivity. It marks a fundamental shift in how software is created, tested, and maintained. LLMs serve as collaborators that augment human capabilities rather than replace human judgment.


The evidence demonstrates substantial practical value. Developers report significant productivity gains, ranging from modest improvements on routine tasks to order-of-magnitude acceleration on specific problems. Code quality improves through automated testing, consistent refactoring, and comprehensive documentation. Legacy systems that were too expensive to modernize become tractable projects. The activation energy required to start new projects decreases, enabling work that would otherwise remain undone.


Yet this technology remains in its adolescence. Current systems exhibit clear limitations in reliability, scalability, and correctness guarantees. The most successful deployments combine LLM capabilities with traditional software engineering practices, rigorous testing, careful review, and validation. Organizations that treat LLMs as assistants rather than autonomous developers achieve the best results.


The trajectory points toward increasingly capable and reliable AI assistance in software development. As models improve, benchmarks become more comprehensive, and integration deepens, LLMs will handle more complex tasks with greater reliability. The partnership between human developers and AI systems will define the future of software engineering, combining human creativity, judgment, and domain expertise with AI capabilities in pattern recognition, code generation, and exhaustive analysis.


For practicing software engineers, the imperative is clear: understanding and effectively using LLM-based tools has become an essential skill. Those who learn to collaborate productively with AI assistants will find their capabilities significantly enhanced. Those who ignore these tools risk falling behind as the industry adopts new workflows and expectations. The revolution in software engineering is not coming; it has arrived and is accelerating. The question is not whether to engage with LLM-based development tools but how to use them most effectively to produce better software faster.

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.