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.

No comments: