A friendly, deep, jargon-light field guide for developers, users and admins who have never touched an agentic AI platform before.
A short note before we begin
This guide is written for three kinds of reader at once. If you're a user who simply wants a clever assistant that can run errands on your own machine, you'll find plain recipes you can copy. If you're an administrator who has to keep the thing safe and running, you'll find the knobs that matter. And if you're a developer who wants to teach Mercury new tricks, you'll find the extension points and real code.
Mercury Agent can be downloaded from https://github.com/ms1963/mercury_agent
What Mercury Agent actually is
Mercury Agent is a self-hosted, extensible agentic AI platform written in TypeScript. That sentence hides three ideas worth unpacking slowly. "Self-hosted" means Mercury runs on your computer or your server, keeps its data in a hidden folder in your home directory, and sends nothing to the outside world except the messages you deliberately forward to whichever AI service you chose. "Agentic" means Mercury doesn't merely chat; it can decide to take actions - read a file, run a shell command, fetch a web page, call an external service - observe the result, and keep going until the job is done. "Platform" means it's not a single program but a small ecosystem: a command-line tool, a web interface, connectors to nineteen chat platforms, multi-agent workflows, a persistent memory, a library of more than seventy-five built-in tools, and a bridge to the Model Context Protocol that works in both directions.
The single most important thing to understand on day one is that Mercury has no brain of its own. It ships with no built-in language model. Think of Mercury as an extremely capable body - hands, eyes, memory, judgement about when to act - that needs you to plug in a brain before it can think. That brain is a Large Language Model (an LLM), and you can supply it from the cloud through providers such as OpenRouter or Abacus.AI ChatLLM, or entirely from your own machine through Ollama or LM Studio. Until you connect at least one real provider, Mercury can start up and show you its interface, but it can't answer a question.
The subsystems you'll meet as you read on fit together like this. A core agent loop decides what to do next and calls tools to do it. A model router chooses which LLM to use for each task so that a trivial question doesn't burn an expensive model. An optional typed decision engine called Jev makes the sharper judgements - which model, how risky a tool call is, whether an incoming message deserves a human - and degrades gracefully to simpler heuristics when it's absent. A gateway layer connects Mercury to Telegram, Slack, Discord, email and many more. A scheduler runs tasks on a cron or in plain English. A workflow engine coordinates several cooperating agents. A voice subsystem turns speech into text and text back into speech. A skills system lets Mercury learn reusable procedures, and a tools system lets it act. Finally, the Model Context Protocol support lets Mercury borrow tools from other programs and lend its own tools to clients such as desktop AI apps.
One honesty note that matches the project's own documentation: as of the current release the core agent loop has been exercised against real LLMs, while the Jev engine, the chat gateways and the voice features are documented and covered by the offline test suite but have not all been proven against live third-party services. Where that matters below, I say so plainly rather than pretending everything has been battle-tested in production.
1. Installing Node.js and then Mercury Agent
Mercury runs on Node.js, the free runtime that executes JavaScript and TypeScript outside a browser, and it needs version 22.5 or newer because it relies on features that only arrived in that release, including the built-in SQLite database. Before anything else, open a terminal and ask Node which version you have.
node -v
If that prints something like v22.5.0 or higher you're ready. If it prints a smaller number or an error, visit https://nodejs.org, download the large green "LTS" button, install it the way you would install any ordinary application, and then run "node -v" once more to confirm the upgrade took hold. This is the only piece of software you ever install by hand; Mercury pulls in everything else it needs on its own.
With Node in place, fetch the Mercury source, step into its folder, install its dependencies and compile it. The three commands below are meant to be run one at a time, and the middle one can take a minute or two the first time because it downloads the project's libraries.
git clone https://github.com/ms1963/mercury_agent.git mercury
cd mercury
npm install
npm run build
The clone step copies the project onto your machine, "npm install" downloads the libraries Mercury depends on, and "npm run build" turns the TypeScript source into the JavaScript that Node actually runs. After the build you can always invoke Mercury through its compiled entry point, which is handy to know when a global shortcut isn't set up.
node packages/cli/dist/bin.js setup
node packages/cli/dist/bin.js serve
Typing that long path every time is tedious, so most people make a global "mercury" command once. The project ships an installer that both builds and links the command for you, and after it runs you can simply type "mercury" from anywhere.
./install.sh
mercury --help
If you would rather not touch your system at all, Mercury runs just as well inside a container, and the data survives restarts because it lives in a named volume rather than inside the container.
docker compose up -d
The default container image is deliberately slim and leaves out the heavier offline voice engines. If you want fully offline speech inside the container you build the voice-enabled variant instead, which additionally bundles ffmpeg, Whisper and Piper at the cost of a larger image.
docker compose --profile voice up -d --build mercury-voice
However you installed it, the very first time you run Mercury you should run its interactive setup, which walks you through creating an administrator account and choosing your first LLM provider. A small but important rule applies in the web interface: the first account that registers becomes the administrator, so register yourself before you expose the interface to anyone else.
mercury setup
Mercury keeps all of its state - your configuration, your conversations, your memory, your skills - in a hidden folder called .mercury inside your home directory. You can move that somewhere else by setting the MERCURY\_HOME environment variable, which is useful when you want several isolated instances or when you keep your home directory small.
2. Giving Mercury a brain: OpenRouter or Ollama
Mercury identifies every model with a two-part name of the form provider/model, for example openai/gpt-4o-mini or ollama/llama3.1. You pick the active one with the "mercury model" command, with the llm.defaultModel configuration key, or with the /model slash command inside a chat. A crucial separation keeps your secrets safe: API keys belong in the file ~/.mercury/.env or in the process environment and never in the configuration file, while the wiring that describes a provider belongs in ~/.mercury/config.yaml. Keeping keys out of config means you can share or back up your config without leaking a secret.
The remote route most people reach for is OpenRouter, a single service that resells hundreds of models behind one key. You drop the key into the environment file and then name an OpenRouter model. Because the key is present, Mercury auto-enables OpenRouter without any further configuration entry, and as a pleasant side effect the optional Jev decision engine becomes available too.
echo 'OPENROUTER_API_KEY=sk-or-...' >> ~/.mercury/.env
mercury model openrouter/openai/gpt-4o-mini
The full model name there reads a little oddly because it's layered: "openrouter" is the Mercury provider, and "openai/gpt-4o-mini" is the model as OpenRouter itself names it, so you can swap in "openrouter/anthropic/claude-3.5-sonnet" or any other model OpenRouter exposes simply by changing the tail.
The local route, which keeps every token on your own machine, is Ollama. You install Ollama from https://ollama.com, pull a model so it exists on disk, and then tell Mercury that the Ollama provider is enabled and which model to use. Ollama needs no API key because it runs locally, which is exactly why you must enable it explicitly: Mercury auto-enables cloud providers when it spots their key in the environment, but a keyless local provider has no key to spot, so you declare it on purpose.
ollama pull llama3.1
mercury config set llm.providers.ollama '{"type":"ollama","enabled":true}'
mercury model ollama/llama3.1
By default Mercury talks to Ollama at http://localhost:11434/v1, which is correct when Ollama runs on the same computer. If your Ollama lives on another machine on your network, add a baseUrl field that points at it, keeping the "/v1" suffix because that's the OpenAI-compatible path Mercury speaks.
mercury config set llm.providers.ollama '{"type":"ollama","baseUrl":"http://192.168.1.50:11434/v1","enabled":true}'
You're not forced to choose one brain forever. You can configure several providers at once and leave llm.defaultModel set to the special value "auto", at which point the model router picks a sensible model for each individual task instead of using a single fixed one. That's how you let cheap models handle easy questions while reserving an expensive model for the hard ones.
3. Configuring Jev, and why you might want to
Jev is Mercury's optional typed decision engine. Where an ordinary LLM writes prose, Jev answers narrow, structured questions - a choice among options, a yes or no, a numeric score - and attaches a confidence to each answer. Mercury uses those crisp judgements in several places at once: to route a task to the right model, to classify whether an incoming instruction looks like a prompt-injection attack, to decide smartly whether a tool call really needs your approval, to triage messages arriving from chat platforms, and to drive retry and reflection decisions when a step goes wrong. The model behind it is typesafe/jev-1.13, reached through OpenRouter, which is why setting your OpenRouter key quietly switches Jev on.
You control Jev with a single configuration key, decision.provider, and its four settings describe a spectrum from automatic to fully offline. The default, "auto", uses Jev only when an OpenRouter key is present and otherwise falls back first to your normal LLM and finally to a safe built-in heuristic, so it's the setting that simply does the right thing. Choosing "jev" forces Jev on and therefore requires the OpenRouter key. Choosing "llm" tells Mercury to make these decisions with your ordinary language model and never call Jev. Choosing "mock" uses only a deterministic heuristic with no network calls at all, which is what the test suite uses.
mercury config set decision.provider auto
The reason to care is partly quality and partly cost and privacy. A dedicated decision model tends to make sharper routing and risk judgements than asking a general chat model to reason about them in prose, and because those judgements are small and structured they are cheap. At the same time Mercury is explicit that it runs perfectly well without Jev - every decision degrades to the configured LLM or to the heuristic - so if you prefer to keep all traffic on a single provider, or to run entirely offline, set decision.provider to "llm" or "mock" and nothing breaks. The current release notes that the Jev engine itself has been exercised in the offline and mock paths rather than extensively against the live decision model, so treat the automatic fallback as a feature, not a disappointment.
4. Integrating external applications such as Telegram
The gateway is the part of Mercury that connects it to chat platforms, and it speaks to a long list of them: Telegram, Discord, Slack, WhatsApp through the Cloud API, Signal through a signal-cli server, Matrix, Mattermost, Microsoft Teams, IRC, email over IMAP and SMTP, SMS through Twilio, Home Assistant, RSS feeds, a generic inbound webhook, the built-in web chat and the terminal itself. The pattern is the same for all of them. You describe one adapter under gateway.adapters in the configuration file, giving its secrets through environment variables so they never sit in the config, you start the server, and the first time an unknown person messages your bot they receive a pairing code that you link to your Mercury account so conversations can follow you across platforms.
Telegram is the gentlest first integration because it uses long polling, which means Mercury reaches out to Telegram and no public URL or webhook is required. You begin inside Telegram itself by talking to the account named BotFather, which hands you a bot token. You then give that token to Mercury, either inline in the adapter config or, better, through the TELEGRAM\_BOT\_TOKEN environment variable, and you make sure the gateway is switched on.
echo 'TELEGRAM_BOT_TOKEN=123456:AA...' >> ~/.mercury/.env
mercury config set gateway.enabled true
mercury config set gateway.adapters.telegram '{"type":"telegram"}'
With the adapter declared you start the server, which runs the web interface, the REST API and the gateway together, and then you message your new bot from your own Telegram account. The bot replies with a pairing code; you claim it once from the terminal, after which your Telegram identity is mapped to your Mercury user and stays mapped.
mercury serve
mercury gateway pair 482913
A nice consequence of pairing is that the slash commands you'll meet in the next section work from Telegram too, so once paired you can type /model or /usage straight from the chat app. Voice memos you send are transcribed automatically, and any message the Jev triage is unsure about is placed in a human review queue rather than acted on blindly. Platforms that receive messages through webhooks rather than polling - Slack, Discord, WhatsApp and the generic webhook among them - additionally need their endpoint reachable from the internet, so for those you also set server.publicUrl; Telegram, being a polling adapter, needs none of that.
5. Conducting a user chat
There are three comfortable ways to talk to Mercury, and they all share the same underlying agent, so a conversation is a conversation wherever you hold it. The quickest is a one-shot question from the terminal, where you pass your message as an argument and Mercury answers once and exits, which is ideal for scripts.
mercury chat "Summarise the README in three sentences"
When you want a back-and-forth you start the interactive read-eval-print loop by running the same command with no message, which drops you into a prompt where each line you type is a new turn and Mercury keeps the context between turns.
mercury chat
For anything visual - watching tool calls happen, browsing past sessions, managing approvals - you run the server and open the web interface in a browser, which also exposes the REST API that other programs can call.
mercury serve --port 3000
Inside any of these surfaces you steer the conversation with slash commands, which behave identically in the terminal, the web chat and every paired chat platform. You begin a clean session with /new or /reset, you inspect or change the model for just this session with /model, and you switch the reasoning style with /pattern, choosing among approaches such as react, plan-execute and reflexion. You re-run your last message with /retry, remove the last exchange with /undo, and halt a long-running agent with /stop. When a session grows large you compress it with /compress, which summarises the history to save context space, and you keep an eye on spend with /usage and /insights. Approvals that are waiting for you appear with /approve and /deny, and you look under the hood with /memory, /tools, /sessions and /debug. A single example shows the shape of them all.
/model ollama/llama3.1
If you never want to memorise any of these, /help prints the list, and /help followed by a topic prints focused guidance on that topic.
6. Using scheduled tasks
Mercury can act on your behalf while you're away by scheduling tasks, and the pleasant surprise is that you can describe the timing in plain English instead of memorising cron syntax. You add a task with "mercury schedule add", giving it a time with the --when option and then the instruction itself as ordinary prose. The scheduler understands phrases such as recurring weekday mornings, fixed intervals and one-off reminders.
mercury schedule add --when "every weekday at 9am" Summarise my inbox
mercury schedule add --when "in 20 minutes" Remind me to stretch
If you prefer the precision of cron, or if a phrase is too unusual for the parser to understand, you can supply a standard five-field cron expression in exactly the same place, and Mercury treats it the same way.
mercury schedule add --when "0 */6 * * *" Check the build status
Results are delivered back to wherever the task came from - the CLI log, the web interface, or a chat platform such as Telegram - and you can redirect delivery explicitly. You manage the whole collection with a family of subcommands that list, edit, pause, resume, delete and run tasks, and editing is a first-class operation so you never have to delete and recreate a schedule just to change one field. Passing a new --when recomputes the next run time.
mercury schedule list
mercury schedule edit 7 --when "every 3 hours" --name "AI News" --task "Summarise top AI headlines"
mercury schedule edit 7 --deliver telegram:123456 --max-retries 5
The same thing is available visually in the Scheduler panel of the web interface, where an Edit button on each row opens an inline editor with the name, timing and task prefilled so you change what you need and press Save.
7. Using workflows
A workflow is how you get several agents to cooperate on one job, and you describe it declaratively in a small YAML file that names a template type and lists the agents involved. The template decides the shape of the collaboration, and Mercury ships a generous set of them: a single agent, a pipeline where each agent feeds the next, a round-robin, a coordinator with workers, a tree, a map-reduce, a router, a shared blackboard, a debate between opposing agents, and a planner paired with an executor. A pipeline is the easiest to picture because the agents simply form an assembly line, and the special token {previous} hands one agent's output to the next while {input} carries the original request.
name: research-report
type: pipeline
agents:
- name: researcher
role: Find facts.
task: "Research: {input}"
- name: writer
role: Write clearly.
task: "Write a report from these notes:\n{previous}"
You run that file by name, passing the topic as the input, and you can equally launch it from the Workflows panel in the web interface. Every run is bounded by budgets - how many sub-agents it may spawn, how deep it may nest, how many total runs it may make - so a misbehaving workflow can't spiral out of control.
mercury workflow run research-report "The history of the transistor"
When a simple pipeline finishes too shallowly for a genuinely hard task, the planner-executor template digs deeper. A planner first breaks the goal into several concrete, ordered steps, an executor then carries out each step in turn while feeding earlier results forward, and a synthesizer writes the final combined answer. If a step fails the planner re-plans once and continues rather than giving up, and each step emits a progress event you can watch. You tune how hard it tries with a small options block.
name: deep-dive
type: planner-executor
options:
minSteps: 3 # always run at least this many steps
targetSteps: 5 # how many steps the planner aims for
maxSteps: 12 # hard cap that is never exceeded
replanOnFailure: true
agents:
- name: planner # breaks the goal into ordered steps
role: Break the goal into clear, ordered steps.
- name: executor # runs each step in turn
role: Carry out one step at a time.
- name: synthesizer # writes the final combined answer
role: Combine the step results into a complete answer.
The maxSteps cap together with the standard run budgets is what prevents a planner-executor from looping forever, which matters because a planning agent that can re-plan is exactly the kind of thing that could otherwise run away.
8. Configuring speech-to-text and text-to-speech
Mercury can listen and speak. It transcribes voice input - microphone recordings from the web interface, voice memos from chat platforms - and it can read its replies aloud. The design goal here is that speech-to-text and text-to-speech are independently swappable between a commercial cloud API and an open-source self-hosted engine with a single configuration change and no code edits, so you're never locked into one vendor. The fastest way to switch is a named preset, where each preset already bundles the correct provider, base URL, command and model for a known engine. You list the presets, apply one for transcription and one for speech, and inspect the result.
mercury voice presets
mercury voice use stt whisper
mercury voice use tts kokoro
mercury voice show
Those three "use" lines illustrate the whole philosophy. The speech-to-text presets range from the commercial OpenAI cloud, through a self-hosted faster-whisper server called speaches, to a fully offline local Whisper command-line tool. The text-to-speech presets range from commercial OpenAI, through self-hosted open-source servers such as openedai and Kokoro-FastAPI, to the offline local Piper engine and the free Microsoft Edge voices. Applying a preset rewrites the entire voice.stt or voice.tts block in one go, which deliberately removes any stale keys left over from the engine you used before.
If you would rather set things by hand, every underlying key remains available, and two patterns cover most needs. To stay OpenAI-compatible but point at your own server, you change only the base URL, because a self-hosted faster-whisper or Kokoro server exposes the very same routes the OpenAI client already speaks.
mercury config set voice.stt.baseUrl http://localhost:8000/v1
mercury config set voice.tts.baseUrl http://localhost:8080/v1
To go fully offline through local command-line engines you switch the provider itself, at which point Mercury shells out to Whisper for transcription and to Piper for speech rather than making any network call.
mercury config set voice.stt.provider whisper
mercury config set voice.tts.provider piper
One caveat worth stating plainly: the voice subsystem is documented and covered by the offline tests, but it has not been exhaustively proven against every live engine, so when you wire in a particular server, verify a single round trip before relying on it in production.
9. Adding skills
A skill is a reusable procedure written in plain language that teaches Mercury how to approach a certain kind of task well. Mechanically a skill is a folder containing a file named SKILL.md in the agentskills.io format, which is a small block of YAML frontmatter carrying a name and a description followed by Markdown instructions. Mercury shows only the short descriptions of your skills to the model as part of its system prompt and loads the full instructions on demand, so having many skills costs little until one is actually needed. A minimal skill looks like this.
---
name: code-review
description: Review a code change for bugs and security issues. Use when the user asks for a review.
metadata: { version: 1, tags: [code, quality] }
---
# Code review
1. Read the files - do not guess.
2. Look for bugs, missing error handling and security issues.
3. Summarise findings with file and line references.
The description line is doing real work: it's the text the model reads when deciding whether this skill is relevant to the task in front of it, so write it as a clear trigger rather than a vague label. You manage skills from the command line, listing what you have, viewing one in full, and installing a skill from a local path or straight from a git URL, and you scaffold a new one with a single command.
mercury skills list
mercury new skill my-skill
mercury skills install https://github.com/someone/a-useful-skill
Bundled skills live under the repository's skills folder and your own live under ~/.mercury/skills. Beyond hand-written skills, Mercury can distil its own from runs that went well, generalising a proven sequence of tool calls into a reusable, parameterised skill. This is switched off by default because it changes the agent's behaviour over time, and when you enable it the distilled skills start life as proposals that must be approved before the agent may reuse them, with each approved skill tracked by its success rate so that a skill which stops working is retired automatically. You turn the feature on, and optionally let good skills auto-approve, through configuration.
skills:
distill:
enabled: true # master switch for distil, match and record
autoApprove: false # keep a human in the loop before reuse
minToolCalls: 2 # a run needs at least this many tool calls to distil
retireBelowSuccessRate: 0.5 # auto-retire a skill that drops below this success rate
10. Adding tools
If skills are knowledge, tools are hands. Mercury ships with around seventy-five built-in tools organised into toolsets for files, shell, web, code, memory, skills, scheduling, media and messaging, and every tool carries a risk level of safe, moderate or dangerous. The risk level drives safety: a dangerous tool requires your approval before it runs unless your policy explicitly allows it, which is how Mercury can be both capable and cautious. You survey and curate the built-in tools from the command line or from the Tools and MCP panel in the web interface.
mercury tools list
mercury tools toolsets
mercury tools disable shell
Adding your own tool doesn't require touching Mercury's source, because any folder that contains a tool.json manifest in the repository's tools directory, in ~/.mercury/tools, or in a directory you list under tools.polyglotDirs automatically becomes a tool. These are called polyglot tools because they can be written in any language: Mercury writes the tool's JSON arguments to the process's standard input and reads its standard output back as the result, treating a non-zero exit code as an error. The manifest describes the tool to the model and tells Mercury how to run it.
{
"name": "slugify",
"description": "Turn a title into a URL-friendly slug.",
"toolset": "polyglot",
"risk": "safe",
"parameters": {
"type": "object",
"properties": { "text": { "type": "string" } },
"required": ["text"]
},
"command": ["node", "main.mjs"],
"requires": ["node"]
}
Two fields in that manifest deserve attention. The risk field decides whether the tool runs freely or passes through approval gating, so set it honestly - a tool that deletes files isn't "safe". The requires field lists the binaries that must be present on the PATH for the tool to work, and Mercury simply hides the tool when they are missing rather than failing at call time. The program that backs the manifest is ordinary code; a tiny Node script that reads the arguments and prints a slug completes the example.
// main.mjs - reads {"text": "..."} from stdin, prints a slug to stdout.
let input = '';
for await (const chunk of process.stdin) {
input += chunk;
}
const { text = '' } = JSON.parse(input || '{}');
const slug = text
.toLowerCase()
.trim()
.replace(/[^a-z0-9]+/g, '-') // non-alphanumerics become single hyphens
.replace(/^-+|-+$/g, ''); // trim leading and trailing hyphens
process.stdout.write(slug);
Rather than create the folder by hand you can scaffold a correct starter in the language of your choice, which writes the manifest and a runnable stub for you.
mercury new tool slugify --lang js
11. Connecting Mercury to external MCP servers
The Model Context Protocol, usually shortened to MCP, is an open standard that lets one program offer tools to another in a uniform way, and Mercury is an MCP client, so it can borrow tools from any MCP server you point it at. You register a server under mcp.servers in the configuration, giving either a command to launch a local stdio server or an HTTP URL for a remote one, and the server's tools then appear inside Mercury with names of the form mcp_<server>_<tool> so you can always see where a tool came from.
So that you don't have to remember exact command lines, Mercury ships curated presets for several common servers - a filesystem server, a fetch server, a GitHub server, a git server and a SQLite server. You list the presets, enable one, and check that it actually connected.
mercury mcp presets
mercury mcp enable github --name gh
mercury mcp status
The presets never contain secrets. Instead they reference placeholders such as ${GITHUB\_TOKEN}, ${MCP\_FS\_ROOT}, ${MCP\_GIT\_REPO} and ${MCP\_SQLITE\_DB}, which Mercury resolves from the environment at the moment it connects, and if a required variable is unset the enable command tells you which one so you can export it first.
export GITHUB_TOKEN=ghp_your_token_here
mercury mcp enable github --name
A safety detail matters here: every preset server is registered as untrusted, which means the output of its tools is treated as untrusted data and remains subject to the same policy and approval engine as everything else. That's the right default, because a tool whose behaviour is defined by someone else's server should not be allowed to bypass your safety rules.
12. Calling Mercury from an MCP client
Mercury isn't only a client but also an MCP server, which means other programs - a desktop AI application, a coding assistant, your own script - can borrow Mercury's seventy-five-plus tools through the same protocol. When you run the server, Mercury exposes its tools at the /mcp endpoint over streamable HTTP. Access is token-controlled, so you first mint a token that carries the mcp scope and then present it as a bearer token on each request.
mercury serve
mercury token create claude --scopes mcp
That command prints a token beginning with mrc\_, and an MCP client reaches Mercury by sending it in the standard Authorization header against the /mcp endpoint of your running server.
Authorization: Bearer mrc_xxxxxxxxxxxxxxxxxxxxxxxx
Some desktop clients prefer to launch a local process and talk to it over standard input and output rather than over HTTP. For them Mercury offers a stdio server mode that you start with a single command, which is the form you typically put into a desktop client's configuration so the client spawns Mercury itself.
mercury mcp serve
13. Extending Mercury as a developer
When configuration isn't enough and you want to add genuine new behaviour, Mercury gives you clean extension points, and the lightest of them is a plugin. A plugin is a small JavaScript module that Mercury loads from ~/.mercury/plugins, and in its setup function it receives an API object through which it registers new capabilities. The example below registers a brand-new tool and a hook that logs every tool call, and it illustrates the shape every plugin follows.
// ~/.mercury/plugins/hello.mjs
export default {
name: 'hello',
version: '1.0.0',
setup(api) {
// Register a new tool the agent can call by name.
api.registerTool({
name: 'hello',
description: 'Say hello',
toolset: 'custom',
risk: 'safe',
parameters: { type: 'object', properties: { who: { type: 'string' } } },
async execute(args) {
return `Hello, ${args.who ?? 'world'}!`;
},
});
// Hooks receive a payload and may return a patch object, or nothing.
api.registerHook('before_tool_call', (payload) => {
api.logger.info('tool', { tool: payload.tool });
});
},
};
The API handed to setup is richer than those two calls suggest. Alongside registerTool and registerHook it offers registerMemoryProvider and registerContextEngine for changing how Mercury remembers, registerLLMProvider and registerDecisionProvider for teaching it to talk to new brains, and registerPattern, registerWorkflowTemplate and registerAdapter for new reasoning styles, new workflow shapes and new chat platforms respectively. The most reliable way to start a real plugin is to let Mercury scaffold an exact, up-to-date skeleton for you rather than copying an example that may drift.
mercury new plugin my-plugin
A gateway adapter is the extension point you reach for when you want Mercury on a chat platform it doesn't yet support. An adapter implements a small, explicit interface - or extends the provided BaseAdapter to inherit the boring parts - whose methods cover the whole life cycle of a connection: starting it and pushing inbound messages into a sink, stopping it cleanly, sending outbound messages, reporting status, and optionally handling a webhook mounted at /webhooks/<name>.
interface Adapter {
readonly name: string;
readonly type: string;
readonly textOnly?: boolean;
start(sink: InboundSink): Promise<void>; // connect and push InboundMessage objects to the sink
stop(): Promise<void>; // disconnect cleanly
send(out: OutboundMessage): Promise<void>; // deliver a reply to the platform
status(): AdapterStatus; // report health for the Integrations panel
handleWebhook?(req: WebhookRequest): Promise<WebhookResponse>; // optional inbound HTTP
}
A design detail that makes adapters pleasant to test is that they perform HTTP through an injected transport rather than calling fetch directly, so a test can substitute a MockTransport and assert on what the adapter would have sent without touching the network. You register an adapter factory from a plugin and then declare it in the configuration just like a built-in one.
api.registerAdapter('myplatform', (config) => new MyAdapter(config));
Two further extension points round out the developer story. A polyglot tool, covered earlier, is the right choice when your logic is easier to write in Python, Go, C++ or Java than in TypeScript. And a custom LLM or decision provider lets you bolt on a backend Mercury has never heard of: an LLMProvider implements the chat and streaming calls for a provider/model id, while a DecisionProvider answers typed questions such as a choice, a boolean or a score together with a confidence. The built-in Jev provider in the source tree is a compact reference you can read while writing your own.
Implementing a client that works with local and remote LLMs
Because so much of Mercury's power comes from the simple idea of one transport feeding many backends, it's worth building that idea yourself in a small, dependency-free client. The program below talks to both a local model server such as Ollama and a remote cloud endpoint such as Abacus.AI ChatLLM or OpenRouter through the single OpenAI "chat completions" wire format, selecting a backend purely by its base URL and an optional key. It mirrors how Mercury itself is organised, and it deliberately has no mocks and no hidden fallbacks: if a backend is unreachable, the call fails loudly. It needs Node.js 22.5 or newer and runs with "node --experimental-strip-types llm-client.ts".
We start with a tiny, explicit vocabulary that every backend shares, so that the rest of the code never has to care which backend it's really talking to. A chat message is a role and some text, a backend is a name, a base URL, a model and an optional key, and a result is normalised down to the text plus a little token accounting.
/** One turn in a conversation, in provider-neutral form. */
export interface ChatMessage {
role: 'system' | 'user' | 'assistant';
content: string;
}
/** Everything needed to reach exactly one backend. */
export interface BackendConfig {
readonly name: string; // human-readable, e.g. "ollama" or "chatllm"
readonly baseUrl: string; // OpenAI-compatible, ends in "/v1", no trailing slash
readonly model: string; // model id that backend understands, e.g. "llama3.1"
readonly apiKey?: string; // bearer token for remote backends; omit for local servers
}
/** Normalised result returned to the caller regardless of backend. */
export interface ChatResult {
readonly text: string;
readonly model: string;
readonly inputTokens: number;
readonly outputTokens: number;
}
A robust client has to distinguish a problem worth retrying from one that's hopeless, so we give transport failures their own error type carrying a retryable flag. A momentary 503 from an overloaded server is retryable; a 401 from a wrong key isn't, and retrying it would only waste time and quota.
/** Raised for transport-level failures; `retryable` guides the retry policy. */
export class LlmError extends Error {
constructor(
message: string,
readonly status: number | undefined,
readonly retryable: boolean,
) {
super(message);
this.name = 'LlmError';
}
}
The client itself is one class with two transports behind a shared request builder. The private helpers assemble the headers - adding the Authorization line only when a key exists, which is exactly what lets the same code serve a keyless local Ollama and a keyed cloud endpoint - and the request body, and then POST it with a timeout, translating every HTTP or network failure into the typed error above.
export class OpenAICompatibleClient {
constructor(private readonly config: BackendConfig) {}
/** Add the Authorization header only when a key is present. */
private headers(): Record<string, string> {
const headers: Record<string, string> = { 'content-type': 'application/json' };
if (this.config.apiKey) {
headers.authorization = `Bearer ${this.config.apiKey}`;
}
return headers;
}
/** Assemble the body shared by the buffered and streaming paths. */
private body(messages: ChatMessage[], options: ChatOptions, stream: boolean): string {
return JSON.stringify({
model: this.config.model,
messages,
temperature: options.temperature ?? 0.7,
max_tokens: options.maxTokens,
stream,
// Ask OpenAI-compatible servers to report token usage in the final chunk.
...(stream ? { stream_options: { include_usage: true } } : {}),
});
}
/** POST with a timeout; turn HTTP/network failures into a typed LlmError. */
private async post(messages: ChatMessage[], options: ChatOptions, stream: boolean): Promise<Response> {
const url = `${this.config.baseUrl}/chat/completions`;
let response: Response;
try {
response = await fetch(url, {
method: 'POST',
headers: this.headers(),
body: this.body(messages, options, stream),
signal: AbortSignal.timeout(120_000),
});
} catch (cause) {
// DNS failure, connection refused (local server down), or timeout.
throw new LlmError(`network error calling ${this.config.name}: ${String(cause)}`, undefined, true);
}
if (!response.ok) {
const detail = (await response.text().catch(() => '')).slice(0, 300);
const retryable = response.status === 429 || response.status >= 500;
throw new LlmError(`${response.status} from ${this.config.name}: ${detail}`, response.status, retryable);
}
return response;
}
}
The options type the methods above refer to is small, shaping a single request with a temperature, an optional token cap, and a callback that receives streamed fragments as they arrive.
/** Options that shape a single request. */
export interface ChatOptions {
readonly temperature?: number; // lower is more deterministic
readonly maxTokens?: number; // hard cap on generated tokens
readonly onDelta?: (fragment: string) => void; // called with each streamed fragment
}
With the plumbing in place, the first public method asks for a complete answer in one buffered response. It reads the JSON the server returns and copies out the text and the token counts, defaulting each field defensively so a slightly different server shape can't crash the caller. These two methods belong inside the class above.
/** Request a complete answer in one buffered JSON response. */
async complete(messages: ChatMessage[], options: ChatOptions = {}): Promise<ChatResult> {
const response = await this.post(messages, options, false);
const json = (await response.json()) as {
model?: string;
choices?: Array<{ message?: { content?: string | null } }>;
usage?: { prompt_tokens?: number; completion_tokens?: number };
};
return {
text: json.choices?.[0]?.message?.content ?? '',
model: json.model ?? this.config.model,
inputTokens: json.usage?.prompt_tokens ?? 0,
outputTokens: json.usage?.completion_tokens ?? 0,
};
}
/** Stream the answer token by token, forwarding each fragment to onDelta. */
async stream(messages: ChatMessage[], options: ChatOptions = {}): Promise<ChatResult> {
const response = await this.post(messages, options, true);
if (!response.body) {
throw new LlmError(`empty stream from ${this.config.name}`, undefined, false);
}
const decoder = new TextDecoder();
let buffer = '';
let text = '';
let inputTokens = 0;
let outputTokens = 0;
for await (const chunk of response.body as unknown as AsyncIterable<Uint8Array>) {
buffer += decoder.decode(chunk, { stream: true });
// Server-Sent-Events are newline-delimited; process every complete line.
let newline: number;
while ((newline = buffer.indexOf('\n')) >= 0) {
const line = buffer.slice(0, newline).replace(/\r$/, '');
buffer = buffer.slice(newline + 1);
if (!line.startsWith('data:')) {
continue;
}
const payload = line.slice('data:'.length).trimStart();
if (payload === '[DONE]') {
break;
}
const event = safeParse(payload);
if (!event) {
continue;
}
const fragment = event.choices?.[0]?.delta?.content;
if (fragment) {
text += fragment;
options.onDelta?.(fragment);
}
if (event.usage) {
inputTokens = event.usage.prompt_tokens ?? inputTokens;
outputTokens = event.usage.completion_tokens ?? outputTokens;
}
}
}
return { text, model: this.config.model, inputTokens, outputTokens };
}
The streaming parser leans on one small helper and one small type. The helper parses a single Server-Sent-Events payload and returns undefined on malformed JSON rather than throwing, because a half-received chunk must not bring the whole stream down.
/** Shape of the streaming chunk fragments we actually read. */
interface StreamChunk {
choices?: Array<{ delta?: { content?: string } }>;
usage?: { prompt_tokens?: number; completion_tokens?: number };
}
/** Parse one SSE payload, returning undefined on malformed JSON. */
function safeParse(payload: string): StreamChunk | undefined {
try {
return JSON.parse(payload) as StreamChunk;
} catch {
return undefined;
}
}
The final piece turns a list of backends into a resilient call. It tries the first backend, retries a retryable failure with exponential backoff and a little jitter so that many clients don't all retry in lockstep, and only then moves on to the next backend; a non-retryable error aborts that backend immediately. Listing a local backend first and a cloud backend second gives you a system that prefers to stay offline and private but reaches for the cloud when the local model is down.
/** Sleep helper used by the backoff loop. */
function delay(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/**
* Try each backend in order. Retry a RETRYABLE failure with backoff and jitter,
* then fall through to the next backend. A non-retryable error (e.g. a 401 on a
* bad key) stops that backend at once, because retrying it would only waste quota.
*/
export async function completeWithFallback(
backends: readonly BackendConfig[],
messages: ChatMessage[],
options: ChatOptions & { retries?: number; backoffMs?: number; jitter?: number } = {},
): Promise<ChatResult> {
const retries = options.retries ?? 2;
const backoffMs = options.backoffMs ?? 500;
const jitter = options.jitter ?? 0.5;
let lastError: unknown;
for (const backend of backends) {
const client = new OpenAICompatibleClient(backend);
for (let attempt = 0; attempt <= retries; attempt++) {
try {
return await client.complete(messages, options);
} catch (error) {
lastError = error;
const canRetry = error instanceof LlmError && error.retryable && attempt < retries;
if (!canRetry) {
break; // non-retryable, or out of attempts: move to the next backend
}
const base = backoffMs * 2 ** attempt;
const sleep = base + Math.random() * base * jitter;
await delay(sleep);
}
}
}
throw new LlmError(`all backends failed; last error: ${String(lastError)}`, undefined, false);
}
To see the whole thing work you build the backend list from the environment, always including a local Ollama and adding a remote ChatLLM only when its key is present, so the example runs fully offline against Ollama alone yet uses the cloud automatically when you have a key. A short main function streams an answer from the first backend and then demonstrates the resilient fallback helper.
/** Build the backend list from the environment: Ollama always, ChatLLM if keyed. */
function backendsFromEnv(): BackendConfig[] {
const backends: BackendConfig[] = [
{
name: 'ollama',
baseUrl: process.env.OLLAMA_BASE_URL ?? 'http://localhost:11434/v1',
model: process.env.OLLAMA_MODEL ?? 'llama3.1',
},
];
const remoteKey = process.env.CHATLLM_API_KEY ?? process.env.ABACUS_API_KEY;
if (remoteKey) {
backends.push({
name: 'chatllm',
baseUrl: 'https://routellm.abacus.ai/v1',
model: 'route-llm',
apiKey: remoteKey,
});
}
return backends;
}
/** Entry point: stream from the first backend, then show the fallback helper. */
async function main(): Promise<void> {
const backends = backendsFromEnv();
const messages: ChatMessage[] = [
{ role: 'system', content: 'You are a concise assistant.' },
{ role: 'user', content: 'In one sentence, what is an agentic AI platform?' },
];
const primary = new OpenAICompatibleClient(backends[0]!);
process.stdout.write(`[streaming from ${backends[0]!.name}]\n`);
const streamed = await primary.stream(messages, {
temperature: 0.2,
onDelta: (fragment) => process.stdout.write(fragment),
});
process.stdout.write(`\n[tokens in=${streamed.inputTokens} out=${streamed.outputTokens}]\n`);
const resilient = await completeWithFallback(backends, messages, { temperature: 0.2 });
process.stdout.write(`[fallback answer] ${resilient.text}\n`);
}
// Run main() only when executed directly, not when imported as a module.
if (process.argv[1] && import.meta.url === `file://${process.argv[1]}`) {
main().catch((error) => {
console.error(error instanceof Error ? error.message : error);
process.exit(1);
});
}
The lesson this program teaches is the same lesson that explains Mercury's whole provider design. Because local and remote model servers all speak the one OpenAI-compatible dialect, the only real difference between "private and offline" and "powerful and in the cloud" is a base URL and whether an Authorization header is attached, and once you accept that, switching or combining them becomes a configuration decision rather than a rewrite.
Ideas for exercises
The fastest way to make all of this stick is to use it on something small and real, so here are a handful of graded challenges. As a gentle start, install Mercury, connect Ollama with a small local model, and hold a short conversation entirely offline, noticing that no data leaves your machine. Next, add an OpenRouter key and leave llm.defaultModel on auto, then ask both a trivial question and a hard one and watch the router send them to different models. For a practical win, create a Telegram bot, pair it, and schedule a task that summarises something each morning and delivers the result to your Telegram chat. To feel the extension points, write a polyglot tool in the language you know best - a currency converter or a word counter is plenty - and watch Mercury offer it to the model. Then teach Mercury a repeatable habit by writing a SKILL.md for a task you do often, such as reviewing a pull request, and confirm the model reaches for it. For a taste of cooperation, write a two-agent pipeline workflow in which one agent researches and another writes, and compare its output to a single agent doing the same job. If you administer a shared instance, connect a read-only filesystem MCP server as a preset and verify that its tools arrive as untrusted and still pass through approval. Finally, for the ambitious, build the local-plus-remote client from the previous section and extend completeWithFallback to record which backend eventually answered, which is the first step towards your own routing policy.
Conclusions
Mercury Agent is best understood as a capable, cautious body waiting for a brain. It gives you a command line, a web interface and nineteen chat gateways through which to talk to it; a scheduler and a workflow engine through which to put it to work unattended and in teams; a voice subsystem, a skills library and a seventy-five-strong toolset through which it perceives and acts; and an MCP bridge through which it both borrows and lends abilities. The optional Jev decision engine sharpens its judgement without ever being mandatory, and the whole system is built so that the choice between local privacy and cloud power is a single base URL rather than a fork in your code. If you remember only two things, remember that Mercury needs a real LLM provider before it can answer, and that it's honest about what has and has not been proven - the core loop has run against real models, while some subsystems are so far verified mainly offline. Start small, connect one brain, hold one conversation, and build outward from there.
Addendum: contributing to Mercury through the GitHub repository
Mercury is an open project under the MIT license, and contributing follows an ordinary, friendly pull-request flow. You begin by forking the repository on GitHub and creating a topic branch from main, naming it after the change you intend to make.
git checkout -b feat/short-description
The guiding principle while you work is the smallest diff that does the job: make your change, match the surrounding code style, and resist the urge to reformat untouched code, because churn hides real changes and breeds regressions. Before you open a pull request you keep the build and the tests green and run the linter, since the project expects all three to pass.
npm run build
npm test
npx eslint .
Whenever you change behaviour you add or update tests for it; the suite runs offline against a deterministic mock provider that the test harness enables for you through MERCURY\_ENABLE\_MOCK, and production code must never enable that mock outside tests. You also update the documentation when user-facing behaviour changes, touching the README, the relevant file under docs, and STATUS.md if a subsystem's tested status moves. Commit messages are short, imperative and type-prefixed, so a new feature reads as "feat: add X", a fix as "fix: handle Y", and documentation as "docs: ...". When you open the pull request you describe what changed and why, link any related issue, keep it focused on one logical change, and - in keeping with the project's culture of honesty - you note explicitly if anything was not tested against real external services such as LLM APIs, chat platforms or the speech engines. That last habit is the heart of the project: Mercury's documentation is deliberately candid about what is proven and what isn't, and your contribution is most valuable when it's candid too.
