Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

Feat/mcp client (#207)

asyfdzakycosmicc3c99ba1c414
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 33416f85..a29f84d2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,10 @@
# Changelog
+## Unreleased
+
+### MCP servers (ADR-029)
+- **MCP servers: Mercury can use tools from Model Context Protocol servers.** Add a local server (`mercury mcp add files --stdio npx -- -y @modelcontextprotocol/server-filesystem ~/Documents`) or a remote one (`--http <url>`), allow the tools you want (`mercury mcp allow`), and the agent can call them next to its built-in tools. Every MCP call asks first in Ask Me mode, and Allow All does not cover MCP tools; only tools you list in `autoApprove` run without a prompt, and only those run in scheduled tasks. Secrets stay in `.env` as `${env:NAME}` references and are masked everywhere they could appear. Local servers get a minimal environment, never Mercury's API keys, and remote servers go through the SSRF guard. Check health with `mercury mcp test`, `mercury doctor --mcp`, `/mcp` in chat, or the new read-only **MCP** dashboard page. The agent's file tools now always ask before writing `mercury.yaml`, `permissions.yaml` or `.env`, even under Allow All. See [MCP Servers](https://mercuryagent.sh/docs/integrations/mcp) and ADR-029.
+
## 1.4.2 — search that finds things, and a research prompt that asks only when you mean it
### Web search
diff --git a/DECISIONS.md b/DECISIONS.md
index 4360531c..47fa61a7 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -260,3 +260,33 @@
- **Context**: Every surface identified a bot by its id and a two-letter monogram derived from it — dashboard, Android client, TUI — because there was nowhere to put a picture: a profile is `bot.yaml` (identity), `persona.md` (character), `permissions.yaml` (what it may do), and nothing else. A fleet of eight bots is a wall of near-identical monograms, and the phone is where a fleet is actually run (ADR-023).
- **Decision**: An avatar is profile data, not settings. One extension-less file `avatar` in the bot's own profile dir — written through a temp file and renamed so a half-written face never serves, `0600`, replacing any previous one. `GET`/`PUT`/`DELETE /api/bots/:id/avatar`: bytes in as `{ data }` (base64, ≤ 2 MB, png/jpeg/webp/gif decided by the signature, never by the client's label), bytes out with the detected type, an `ETag` for cache validation, and `hasAvatar` on `getStatusSummaries()` so a client needs no probe per bot. A write or a delete rebroadcasts the roster frame, so every open dashboard learns the change at once. Nothing is added to `bot.yaml`: an absent file *is* "no custom avatar", which keeps an exported profile without a face byte-identical, and deleting a bot deletes its face along with the directory.
- **Consequence**: Clients stop inventing identity, and the monogram becomes a fallback rather than the only option. The extension-less name is the point: the format is decided by the bytes, so a webp re-upload can never be served as png because a stale filename said so. Not in this ADR: an avatar for the owner (there is one), generated faces, cropping or thumbnail derivatives — the client scales, and a 2 MB cap keeps that honest.
+
+## ADR-029: MCP client — official v2 SDK, owner-gated tools
+
+- **Context**: Most third-party agent integrations now ship as Model Context Protocol servers, and Mercury had no MCP support at all: tools were the fixed set registered in `CapabilityRegistry.registerAll()`. Phase 1 makes Mercury an MCP client. The SDK options named in the issue had moved on by the time work started. `@ai-sdk/mcp` 2.0.x targets AI SDK 7 (`@ai-sdk/provider` 4.x), while Mercury runs `ai@6`, whose matching line is `@ai-sdk/mcp` 1.0.x. `@modelcontextprotocol/sdk` 1.32 is the maintenance branch. The current official client is `@modelcontextprotocol/client` 2.x. The permission model (ADR-016) has to cover tools whose names, descriptions and results come from a third party.
+- **Decision**:
+ - **SDK.** Use `@modelcontextprotocol/client` 2.x. Its Streamable HTTP transport takes a custom `fetch`, so the SSRF guard sits in the request path. It refreshes tools on `tools/list_changed` (`listChanged.tools.onChanged`), backs off on stream reconnects, and keeps stdio in a separate `./stdio` entry. The default `versionNegotiation: 'legacy'` (the 2025 handshake) is used for now. Mercury writes its own MCP→AI SDK tool wrapper, because every call has to be wrapped anyway for the permission gate, naming, result caps and schema skipping.
+ - **Transports.** stdio and Streamable HTTP. Legacy SSE is left out.
+ - **Tool names.** `mcp__<server>__<tool>`. Server ids match `^[a-z][a-z0-9-]{0,23}$`. Tool parts are sanitised to `[A-Za-z0-9_-]` and the whole name is capped at 64 characters. A truncated or colliding name gets a 6-character hash suffix, and a reverse map keeps calls on the original name.
+ - **Visibility.** A server's tools are hidden until listed in `tools.allow` (`["*"]` for all). `tools.deny` always wins. Bots, plan mode and channel members get no MCP tools in Phase 1.
+ - **Approval.** There is no trust flag. Every MCP call asks in Ask Me mode, and Allow All never covers MCP tools. The only way to skip the prompt is `tools.autoApprove`: exact tool names, no wildcards, set by the owner. A tool that appears later through `list_changed` therefore never inherits approval. Unattended runs (internal turns, scheduled tasks, sub-agents) may only run `autoApprove` tools. Annotations a server sends, such as `readOnlyHint`, never change permissions.
+ - **Process and secrets.** A stdio server starts from the SDK's `getDefaultEnvironment()` plus its own configured `env`, never the daemon's environment, so provider keys loaded from `.env` never reach a third-party process. `${env:NAME}` references are resolved at connect time only, never in `loadConfig`, because `saveConfig` rewrites the whole file and would otherwise write secrets into YAML. Resolved values are registered with the redaction layer.
+ - **HTTP.** Requests go through the SSRF guard. Private and loopback targets need a per-server `allowPrivate: true`, which only the owner can set.
+ - **Lifecycle.** The process that runs the Agent owns the connections: the daemon (ADR-024), or the terminal where no daemon runs. Servers connect in the background at boot with a timeout, so one broken server never blocks startup or other tools.
+ - **Results.** Converted to strings, so the existing compaction can shrink them. Results are capped, and image and audio blocks become placeholders for now.
+ - **Configuration.** Adding or enabling a server is an owner action through `mercury.yaml` or `mercury mcp …`. The agent has no tool for it.
+- **Spike results** (Windows x64, Node 22.12, Bun 1.3.8):
+ - The v2 client connects, lists tools, calls them and receives `tools/list_changed` over stdio. Over Streamable HTTP it uses a caller-supplied `fetch` with static headers. These are covered by `src/capabilities/mcp/sdk-smoke.test.ts` against a dependency-free fixture server.
+ - The same client works under Bun and inside a `bun build --compile` binary. In the binary it starts a server both directly and through a `.cmd` shim (how `npx` runs on Windows), and `npx.cmd` resolves under `getDefaultEnvironment()`.
+ - The client adds about 0.5 MB to a compiled binary.
+ - It brings zod 4 as its own nested dependency; Mercury's zod 3 is untouched.
+ - Termux was not tested.
+- **Alternatives considered**:
+ - `@ai-sdk/mcp` 1.0.x converts tools for us. But it has no `fetch` override for the SSRF guard, doesn't receive notifications, and would have to move to 2.x together with AI SDK 7.
+ - `@modelcontextprotocol/sdk` 1.32 has a similar API, but it is on the maintenance branch and depends on server-side packages (express, hono, cors).
+ - A per-server `trust: trusted | untrusted` flag adds a second axis that decides whether Allow All applies. The exact-name `autoApprove` list does the same job with one rule and can't silently widen.
+ - Treating MCP tools like built-in tools would let Allow All cover third-party code with no prompt.
+- **Consequence**: Owners can use the MCP ecosystem without a hand-written capability per integration. Every third-party call is visible in Ask Me mode unless the owner named the tool in `autoApprove`. The cost is a prompt per call for servers the owner hasn't pre-approved, even under Allow All. That is deliberate. Maintenance owned by Mercury:
+ - Any new place that filters tools by name (plan mode, members, bots, sub-agents) must decide how it treats the `mcp__` prefix.
+ - Text from an MCP server (descriptions, results, errors) is untrusted input and must never be used to make a permission decision.
+ - Resources, prompts, sampling, OAuth, images in results, bot access and the 2026-07-28 protocol (`versionNegotiation: 'auto'`) are follow-ups.
diff --git a/package-lock.json b/package-lock.json
index f62d2c14..2aecd7fc 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -15,6 +15,7 @@
"@ai-sdk/openai": "^3.0.53",
"@grammyjs/auto-retry": "^2.0.2",
"@hono/node-server": "^2.0.0",
+ "@modelcontextprotocol/client": "^2.3.1",
"@slack/bolt": "^4.7.3",
"@types/ws": "^8.18.1",
"ai": "^6.0.168",
@@ -799,6 +800,54 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "node_modules/@modelcontextprotocol/client": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz",
+ "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.8",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/client/node_modules/zod": {
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz",
+ "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==",
+ "license": "Apache-2.0",
+ "dependencies": {
+ "zod": "^4.2.0"
+ },
+ "engines": {
+ "node": ">=20"
+ }
+ },
+ "node_modules/@modelcontextprotocol/core/node_modules/zod": {
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
"node_modules/@opentelemetry/api": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
@@ -2169,6 +2218,20 @@
"node": ">=6.6.0"
}
},
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -2514,6 +2577,18 @@
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw==",
"license": "MIT"
},
+ "node_modules/eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "license": "MIT",
+ "dependencies": {
+ "eventsource-parser": "^3.0.1"
+ },
+ "engines": {
+ "node": ">=18.0.0"
+ }
+ },
"node_modules/eventsource-parser": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.8.tgz",
@@ -3110,6 +3185,21 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "license": "ISC"
+ },
+ "node_modules/jose": {
+ "version": "6.2.13",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz",
+ "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ==",
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/panva"
+ }
+ },
"node_modules/joycon": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
@@ -3664,6 +3754,15 @@
"node": "^12.20.0 || ^14.13.1 || >=16.0.0"
}
},
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/path-to-regexp": {
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
@@ -3752,6 +3851,15 @@
"node": ">= 6"
}
},
+ "node_modules/pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=16.20.0"
+ }
+ },
"node_modules/pkg-types": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
@@ -4283,6 +4391,27 @@
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw==",
"license": "ISC"
},
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
"node_modules/shell-quote": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz",
@@ -5640,6 +5769,21 @@
"webidl-conversions": "^3.0.0"
}
},
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
@@ -6184,6 +6328,42 @@
"@jridgewell/sourcemap-codec": "^1.4.14"
}
},
+ "@modelcontextprotocol/client": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/client/-/client-2.3.1.tgz",
+ "integrity": "sha512-mIGZXpHsjnZ6lD+gD/WCMpR5k8yVQQ8nNFH1N0Srf7AvnwTUMYD6pvTY8ng2+He5FfV7YMZLmrjL7cLa/cc3dQ==",
+ "requires": {
+ "@modelcontextprotocol/core": "2.3.1",
+ "cross-spawn": "^7.0.5",
+ "eventsource": "^3.0.2",
+ "eventsource-parser": "^3.0.8",
+ "jose": "^6.1.3",
+ "pkce-challenge": "^5.0.0",
+ "zod": "^4.2.0"
+ },
+ "dependencies": {
+ "zod": {
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="
+ }
+ }
+ },
+ "@modelcontextprotocol/core": {
+ "version": "2.3.1",
+ "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.3.1.tgz",
+ "integrity": "sha512-laVmIhPGpWi7rG9q+0UigblRN0Hws/Yjlb6qLFtVqryXVLkc4h+yN8z731POD2LnAGQlFe7/tXhUm7Bi0YB91g==",
+ "requires": {
+ "zod": "^4.2.0"
+ },
+ "dependencies": {
+ "zod": {
+ "version": "4.6.7",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",
+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg=="
+ }
+ }
+ },
"@opentelemetry/api": {
"version": "1.9.1",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.1.tgz",
@@ -7087,6 +7267,16 @@
"resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.2.2.tgz",
"integrity": "sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg=="
},
+ "cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "requires": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ }
+ },
"csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
@@ -7326,6 +7516,14 @@
"resolved": "https://registry.npmjs.org/eventemitter3/-/eventemitter3-5.0.4.tgz",
"integrity": "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="
},
+ "eventsource": {
+ "version": "3.0.7",
+ "resolved": "https://registry.npmjs.org/eventsource/-/eventsource-3.0.7.tgz",
+ "integrity": "sha512-CRT1WTyuQoD771GW56XEZFQ/ZoSfWid1alKGDYMmkt2yl8UXrVR4pspqWNEcqKvVIzg6PAltWjxcSSPrboA4iA==",
+ "requires": {
+ "eventsource-parser": "^3.0.1"
+ }
+ },
"eventsource-parser": {
"version": "3.0.8",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.8.tgz",
@@ -7695,6 +7893,16 @@
"resolved": "https://registry.npmjs.org/is-stream/-/is-stream-2.0.1.tgz",
"integrity": "sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg=="
},
+ "isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw=="
+ },
+ "jose": {
+ "version": "6.2.13",
+ "resolved": "https://registry.npmjs.org/jose/-/jose-6.2.13.tgz",
+ "integrity": "sha512-7TIg10ZE1x82YediN+lcrPNvGMKge9yFHQD+Qho/b8y2adfugU3AsvvHfxV0fzyFllT6l9xCjf4RWY9g/Z9PJQ=="
+ },
"joycon": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz",
@@ -8076,6 +8284,11 @@
"integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==",
"dev": true
},
+ "path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="
+ },
"path-to-regexp": {
"version": "8.4.2",
"resolved": "https://registry.npmjs.org/path-to-regexp/-/path-to-regexp-8.4.2.tgz",
@@ -8142,6 +8355,11 @@
"integrity": "sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA==",
"dev": true
},
+ "pkce-challenge": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/pkce-challenge/-/pkce-challenge-5.0.1.tgz",
+ "integrity": "sha512-wQ0b/W4Fr01qtpHlqSqspcj3EhBvimsdh0KlHhH8HRZnMsEa0ea2fTULOXOS9ccQr3om+GcGRk4e+isrZWV8qQ=="
+ },
"pkg-types": {
"version": "1.3.1",
"resolved": "https://registry.npmjs.org/pkg-types/-/pkg-types-1.3.1.tgz",
@@ -8462,6 +8680,19 @@
"resolved": "https://registry.npmjs.org/setprototypeof/-/setprototypeof-1.2.0.tgz",
"integrity": "sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw=="
},
+ "shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "requires": {
+ "shebang-regex": "^3.0.0"
+ }
+ },
+ "shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A=="
+ },
"shell-quote": {
"version": "1.12.0",
"resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.12.0.tgz",
@@ -9229,6 +9460,14 @@
"webidl-conversions": "^3.0.0"
}
},
+ "which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "requires": {
+ "isexe": "^2.0.0"
+ }
+ },
"why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
diff --git a/package.json b/package.json
index 4e650d0d..2426a30a 100644
--- a/package.json
+++ b/package.json
@@ -71,6 +71,7 @@
"@ai-sdk/openai": "^3.0.53",
"@grammyjs/auto-retry": "^2.0.2",
"@hono/node-server": "^2.0.0",
+ "@modelcontextprotocol/client": "^2.3.1",
"@slack/bolt": "^4.7.3",
"@types/ws": "^8.18.1",
"ai": "^6.0.168",
diff --git a/src/bots/registry-factory.ts b/src/bots/registry-factory.ts
index 74f47b34..928bf634 100644
--- a/src/bots/registry-factory.ts
+++ b/src/bots/registry-factory.ts
@@ -2,6 +2,7 @@ import { homedir } from 'node:os';
import { mkdirSync } from 'node:fs';
import { resolve } from 'node:path';
import { CapabilityRegistry } from '../capabilities/registry.js';
+import { isMcpToolName } from '../capabilities/mcp/naming.js';
import type { SkillLoader } from '../skills/loader.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import type { MercuryConfig } from '../utils/config.js';
@@ -152,7 +153,7 @@ export function filterBotTools(all: Record<string, any>, manifest: BotManifest,
const deny = new Set(gate.deny ?? []);
const out: Record<string, any> = {};
for (const [name, tool] of Object.entries(all)) {
- if (ALWAYS_STRIPPED.has(name)) continue;
+ if (ALWAYS_STRIPPED.has(name) || isMcpToolName(name)) continue;
if (deny.has(name)) continue;
// Plugin tools are opt-in for bots (fail-closed): only an explicit allow
// entry ("<plugin>__<tool>" or "<plugin>__*") lets a bot see one. A
diff --git a/src/capabilities/mcp/admin.test.ts b/src/capabilities/mcp/admin.test.ts
new file mode 100644
index 00000000..ca6d4791
--- /dev/null
+++ b/src/capabilities/mcp/admin.test.ts
@@ -0,0 +1,214 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+
+const home = await vi.hoisted(async () => {
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join: joinPath } = await import('node:path');
+ const dir = mkdtempSync(joinPath(tmpdir(), 'mercury-mcp-admin-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const admin = await import('./admin.js');
+const { loadConfig, saveConfig } = await import('../../utils/config.js');
+type McpServerStatus = import('./types.js').McpServerStatus;
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+const join2 = (...parts: string[]) => parts.join('');
+
+describe('buildServerConfig', () => {
+ it('builds a stdio server from CLI options', () => {
+ expect(
+ admin.buildServerConfig({
+ stdio: 'npx',
+ args: ['-y', 'server-github'],
+ env: ['GITHUB_TOKEN=${env:GITHUB_TOKEN}'],
+ allow: 'search_issues, get_issue',
+ autoApprove: 'search_issues',
+ }),
+ ).toEqual({
+ transport: 'stdio',
+ command: 'npx',
+ args: ['-y', 'server-github'],
+ env: { GITHUB_TOKEN: '${env:GITHUB_TOKEN}' },
+ tools: { allow: ['search_issues', 'get_issue'], autoApprove: ['search_issues'] },
+ });
+ });
+
+ it('builds an http server from CLI options', () => {
+ expect(
+ admin.buildServerConfig({
+ http: 'http://127.0.0.1:8080/mcp',
+ header: ['Authorization: Bearer ${env:DOCS_TOKEN}'],
+ allowPrivate: true,
+ disabled: true,
+ }),
+ ).toEqual({
+ transport: 'http',
+ url: 'http://127.0.0.1:8080/mcp',
+ headers: { Authorization: 'Bearer ${env:DOCS_TOKEN}' },
+ allowPrivate: true,
+ enabled: false,
+ });
+ });
+
+ it('rejects mixed or missing transports and misplaced options', () => {
+ expect(() => admin.buildServerConfig({})).toThrow('Pass exactly one of --stdio <command> or --http <url>');
+ expect(() => admin.buildServerConfig({ stdio: 'a', http: 'https://x' })).toThrow('Pass exactly one');
+ expect(() => admin.buildServerConfig({ stdio: 'a', header: ['A: b'] })).toThrow('--header only applies');
+ expect(() => admin.buildServerConfig({ http: 'https://x', env: ['A=b'] })).toThrow('--env only applies');
+ expect(() => admin.buildServerConfig({ http: 'https://x', args: ['x'] })).toThrow('Command arguments only apply');
+ expect(() => admin.buildServerConfig({ stdio: 'a', env: ['NOVALUE'] })).toThrow('Invalid --env "NOVALUE"');
+ });
+});
+
+describe('editing servers', () => {
+ it('adds, enables, disables, allows, disallows and removes', () => {
+ const config: Parameters<typeof admin.addServer>[0] = {};
+ expect(admin.addServer(config, 'fx', { transport: 'stdio', command: 'node' })).toEqual([]);
+ expect(() => admin.addServer(config, 'fx', { transport: 'stdio', command: 'node' })).toThrow('already exists');
+ expect(() => admin.addServer(config, 'Bad_Id', { transport: 'stdio', command: 'node' })).toThrow(/server id must match/);
+
+ expect(admin.setServerEnabled(config, 'fx', false).enabled).toBe(false);
+ expect(admin.setServerEnabled(config, 'fx', true).enabled).toBeUndefined();
+
+ admin.allowTools(config, 'fx', ['echo', 'add']);
+ admin.allowTools(config, 'fx', ['echo']);
+ expect(config.mcp?.servers?.fx?.tools?.allow).toEqual(['echo', 'add']);
+
+ config.mcp!.servers!.fx!.tools!.autoApprove = ['echo'];
+ admin.disallowTools(config, 'fx', ['echo']);
+ expect(config.mcp?.servers?.fx?.tools).toEqual({ allow: ['add'], autoApprove: [] });
+
+ admin.allowTools(config, 'fx', ['*']);
+ admin.disallowTools(config, 'fx', ['add']);
+ expect(config.mcp?.servers?.fx?.tools?.deny).toEqual(['add']);
+ admin.allowTools(config, 'fx', ['add']);
+ expect(config.mcp?.servers?.fx?.tools?.deny).toEqual([]);
+
+ admin.removeServer(config, 'fx');
+ expect(config.mcp?.servers).toEqual({});
+ expect(() => admin.removeServer(config, 'fx')).toThrow('No MCP server named "fx"');
+ });
+
+ it('returns literal-secret warnings when adding', () => {
+ const warnings = admin.addServer({}, 'gh', {
+ transport: 'stdio',
+ command: 'npx',
+ env: { GITHUB_TOKEN: join2('ghp_', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '1234') },
+ });
+ expect(warnings).toHaveLength(1);
+ expect(warnings[0]).toMatch(/GITHUB_TOKEN looks like a literal secret/);
+ });
+
+ it('warns when adding an auto-approved tool that is not allowed', () => {
+ const warnings = admin.addServer({}, 'docs', admin.buildServerConfig({ http: 'https://x.example/mcp', autoApprove: 'search' }));
+ expect(warnings).toEqual([
+ `mcp.servers.docs.tools.autoApprove: "search" is not allowed, so the agent can't see it; add it to tools.allow`,
+ ]);
+ });
+
+ it('keeps ${env:} references literal through a config save', () => {
+ const config = loadConfig();
+ admin.addServer(config, 'docs', {
+ transport: 'http',
+ url: 'https://mcp.example.com/mcp',
+ headers: { Authorization: 'Bearer ${env:DOCS_TOKEN}' },
+ });
+ process.env.DOCS_TOKEN = join2('docs-token-', 'never-written');
+ saveConfig(config);
+ const yaml = readFileSync(join(home, 'mercury.yaml'), 'utf-8');
+ expect(yaml).toContain('Bearer ${env:DOCS_TOKEN}');
+ expect(yaml).not.toContain('never-written');
+ expect(loadConfig().mcp?.servers?.docs?.headers).toEqual({ Authorization: 'Bearer ${env:DOCS_TOKEN}' });
+ delete process.env.DOCS_TOKEN;
+ });
+});
+
+describe('formatting', () => {
+ it('lists servers with masked literal values', () => {
+ const lines = admin.formatServerList({
+ mcp: {
+ servers: {
+ gh: {
+ transport: 'stdio',
+ command: 'npx',
+ args: ['-y', 'server github'],
+ env: { GITHUB_TOKEN: '${env:GITHUB_TOKEN}', MODE: 'read-only-mode' },
+ tools: { allow: ['search_issues'], autoApprove: ['search_issues'] },
+ },
+ docs: {
+ transport: 'http',
+ url: 'https://mcp.example.com/mcp?token=abc',
+ headers: { 'X-Key': 'literal-header-value' },
+ allowPrivate: true,
+ enabled: false,
+ },
+ },
+ },
+ });
+ expect(lines).toEqual([
+ 'gh stdio enabled npx -y "server github"',
+ ' tools: allow search_issues · auto-approve search_issues',
+ ' env: GITHUB_TOKEN=${env:GITHUB_TOKEN}, MODE=read****mode',
+ 'docs http disabled https://mcp.example.com/mcp',
+ ' tools: none allowed',
+ ' headers: X-Key=lite****alue',
+ ' private network: allowed',
+ ]);
+ expect(admin.formatServerList({})[0]).toMatch(/^No MCP servers configured/);
+ });
+
+ const statuses: McpServerStatus[] = [
+ {
+ id: 'gh',
+ transport: 'stdio',
+ enabled: true,
+ state: 'connected',
+ target: 'npx',
+ toolCount: 3,
+ tools: [
+ { name: 'search_issues', exposedName: 'mcp__gh__search_issues', allowed: true, autoApprove: true },
+ { name: 'create_issue', exposedName: 'mcp__gh__create_issue', allowed: false, autoApprove: false },
+ { name: 'odd', exposedName: 'mcp__gh__odd', allowed: true, autoApprove: false, skipped: 'input schema is not an object' },
+ ],
+ },
+ { id: 'docs', transport: 'http', enabled: true, state: 'failed', target: 'https://mcp.example.com', error: 'env DOCS_TOKEN is not set', toolCount: 0, tools: [] },
+ { id: 'off', transport: 'stdio', enabled: false, state: 'disabled', target: 'node', toolCount: 0, tools: [] },
+ ];
+
+ it('summarises server status for /mcp', () => {
+ expect(admin.formatMcpChatStatus(statuses, '')).toBe(
+ [
+ '**MCP servers:**',
+ '',
+ '• gh: connected, 3 tools, 1 allowed — npx',
+ '• docs: failed — env DOCS_TOKEN is not set — https://mcp.example.com',
+ '• off: disabled — node',
+ '',
+ 'Details: /mcp tools <server>',
+ ].join('\n'),
+ );
+ expect(admin.formatMcpChatStatus([], '')).toMatch(/^No MCP servers configured/);
+ });
+
+ it('lists tools for /mcp tools <server>', () => {
+ expect(admin.formatMcpChatStatus(statuses, 'tools gh')).toBe(
+ [
+ '**gh** tools:',
+ '',
+ '• search_issues → mcp__gh__search_issues (allowed, auto-approve)',
+ '• create_issue → mcp__gh__create_issue (hidden)',
+ '• odd → mcp__gh__odd (skipped: input schema is not an object)',
+ ].join('\n'),
+ );
+ expect(admin.formatMcpChatStatus(statuses, 'tools nope')).toBe('Usage: /mcp tools <server>. Servers: gh, docs, off');
+ });
+
+ it('quotes stdio arguments that contain spaces', () => {
+ expect(admin.formatStdioCommand({ transport: 'stdio', command: 'node', args: ['a b', 'c'] })).toBe('node "a b" c');
+ });
+});
diff --git a/src/capabilities/mcp/admin.ts b/src/capabilities/mcp/admin.ts
new file mode 100644
index 00000000..d24804a9
--- /dev/null
+++ b/src/capabilities/mcp/admin.ts
@@ -0,0 +1,220 @@
+import { redactSecrets } from '../../utils/redact.js';
+import { validateMcpConfig } from './config.js';
+import type { McpConfig, McpServerConfig, McpServerStatus } from './types.js';
+
+export interface ConfigWithMcp {
+ mcp?: McpConfig;
+}
+
+export interface AddServerOptions {
+ stdio?: string;
+ http?: string;
+ args?: string[];
+ env?: string[];
+ header?: string[];
+ cwd?: string;
+ allow?: string;
+ autoApprove?: string;
+ allowPrivate?: boolean;
+ disabled?: boolean;
+}
+
+const ENV_REF = /\$\{env:[A-Za-z_][A-Za-z0-9_]*\}/;
+
+export function splitList(value: string | undefined): string[] {
+ return (value ?? '')
+ .split(',')
+ .map((item) => item.trim())
+ .filter((item) => item.length > 0);
+}
+
+function parsePairs(entries: string[] | undefined, separator: '=' | ':', label: string): Record<string, string> | undefined {
+ if (!entries?.length) return undefined;
+ const out: Record<string, string> = {};
+ for (const entry of entries) {
+ const index = entry.indexOf(separator);
+ const key = index > 0 ? entry.slice(0, index).trim() : '';
+ if (!key) throw new Error(`Invalid ${label} "${entry}": expected NAME${separator}value`);
+ out[key] = entry.slice(index + 1).trim();
+ }
+ return out;
+}
+
+export function buildServerConfig(options: AddServerOptions): McpServerConfig {
+ if (Boolean(options.stdio) === Boolean(options.http)) {
+ throw new Error('Pass exactly one of --stdio <command> or --http <url>');
+ }
+ const allow = splitList(options.allow);
+ const autoApprove = splitList(options.autoApprove);
+ const tools = allow.length || autoApprove.length ? { allow, autoApprove } : undefined;
+ const enabled = options.disabled ? false : undefined;
+ if (options.stdio) {
+ if (options.header?.length) throw new Error('--header only applies to --http servers');
+ if (options.allowPrivate) throw new Error('--allow-private only applies to --http servers');
+ return stripUndefined({
+ transport: 'stdio',
+ command: options.stdio,
+ args: options.args?.length ? options.args : undefined,
+ env: parsePairs(options.env, '=', '--env'),
+ cwd: options.cwd,
+ enabled,
+ tools,
+ });
+ }
+ if (options.args?.length) throw new Error('Command arguments only apply to --stdio servers');
+ if (options.env?.length) throw new Error('--env only applies to --stdio servers');
+ if (options.cwd) throw new Error('--cwd only applies to --stdio servers');
+ return stripUndefined({
+ transport: 'http',
+ url: options.http,
+ headers: parsePairs(options.header, ':', '--header'),
+ allowPrivate: options.allowPrivate ? true : undefined,
+ enabled,
+ tools,
+ });
+}
+
+function stripUndefined(server: McpServerConfig): McpServerConfig {
+ return Object.fromEntries(Object.entries(server).filter(([, value]) => value !== undefined)) as unknown as McpServerConfig;
+}
+
+function servers(config: ConfigWithMcp): Record<string, McpServerConfig> {
+ if (!config.mcp) config.mcp = {};
+ if (!config.mcp.servers) config.mcp.servers = {};
+ return config.mcp.servers;
+}
+
+export function getServer(config: ConfigWithMcp, id: string): McpServerConfig {
+ const server = config.mcp?.servers?.[id];
+ if (!server) throw new Error(`No MCP server named "${id}". Run \`mercury mcp list\` to see configured servers.`);
+ return server;
+}
+
+export function addServer(config: ConfigWithMcp, id: string, server: McpServerConfig): string[] {
+ if (config.mcp?.servers?.[id]) throw new Error(`An MCP server named "${id}" already exists`);
+ const validation = validateMcpConfig({ servers: { [id]: server } });
+ if (validation.problems.length) throw new Error(validation.problems[0]);
+ servers(config)[id] = server;
+ return validation.warnings;
+}
+
+export function removeServer(config: ConfigWithMcp, id: string): void {
+ getServer(config, id);
+ delete servers(config)[id];
+}
+
+export function setServerEnabled(config: ConfigWithMcp, id: string, enabled: boolean): McpServerConfig {
+ const server = getServer(config, id);
+ if (enabled) delete server.enabled;
+ else server.enabled = false;
+ return server;
+}
+
+export function allowTools(config: ConfigWithMcp, id: string, tools: string[]): McpServerConfig {
+ const server = getServer(config, id);
+ const filter = (server.tools ??= {});
+ filter.allow = [...new Set([...(filter.allow ?? []), ...tools])];
+ if (filter.deny) filter.deny = filter.deny.filter((tool) => !tools.includes(tool));
+ return server;
+}
+
+export function disallowTools(config: ConfigWithMcp, id: string, tools: string[]): McpServerConfig {
+ const server = getServer(config, id);
+ const filter = (server.tools ??= {});
+ const wildcard = filter.allow?.includes('*') === true;
+ filter.allow = (filter.allow ?? []).filter((tool) => !tools.includes(tool));
+ if (filter.autoApprove) filter.autoApprove = filter.autoApprove.filter((tool) => !tools.includes(tool));
+ const stillWildcard = wildcard && filter.allow.includes('*');
+ const named = tools.filter((tool) => tool !== '*');
+ if (stillWildcard && named.length) {
+ filter.deny = [...new Set([...(filter.deny ?? []), ...named])];
+ }
+ return server;
+}
+
+export function maskValue(value: string): string {
+ if (ENV_REF.test(value)) return redactSecrets(value);
+ if (value.length <= 8) return '****';
+ return `${value.slice(0, 4)}****${value.slice(-4)}`;
+}
+
+function quoteArg(arg: string): string {
+ return /[\s"']/.test(arg) ? JSON.stringify(arg) : arg;
+}
+
+export function formatStdioCommand(server: McpServerConfig): string {
+ return [server.command ?? '', ...(server.args ?? [])].map(quoteArg).join(' ');
+}
+
+function formatTarget(server: McpServerConfig): string {
+ if (server.transport === 'stdio') return redactSecrets(formatStdioCommand(server));
+ try {
+ const url = new URL(server.url ?? '');
+ return `${url.origin}${url.pathname}`;
+ } catch {
+ return '(invalid url)';
+ }
+}
+
+function formatPairs(values: Record<string, string> | undefined): string {
+ return Object.entries(values ?? {})
+ .map(([key, value]) => `${key}=${maskValue(value)}`)
+ .join(', ');
+}
+
+export function formatServerList(config: ConfigWithMcp): string[] {
+ const entries = Object.entries(config.mcp?.servers ?? {});
+ if (!entries.length) return ['No MCP servers configured. Add one with `mercury mcp add <id> --stdio <command>` or `--http <url>`.'];
+ const lines: string[] = [];
+ for (const [id, server] of entries) {
+ const state = server.enabled === false ? 'disabled' : 'enabled';
+ lines.push(`${id} ${server.transport} ${state} ${formatTarget(server)}`);
+ const allow = server.tools?.allow ?? [];
+ const deny = server.tools?.deny ?? [];
+ const autoApprove = server.tools?.autoApprove ?? [];
+ lines.push(` tools: ${allow.length ? `allow ${allow.join(', ')}` : 'none allowed'}`
+ + (deny.length ? ` · deny ${deny.join(', ')}` : '')
+ + (autoApprove.length ? ` · auto-approve ${autoApprove.join(', ')}` : ''));
+ if (server.env && Object.keys(server.env).length) lines.push(` env: ${formatPairs(server.env)}`);
+ if (server.headers && Object.keys(server.headers).length) lines.push(` headers: ${formatPairs(server.headers)}`);
+ if (server.allowPrivate) lines.push(' private network: allowed');
+ }
+ return lines;
+}
+
+export function formatStatusLine(status: McpServerStatus): string {
+ const target = status.target ? ` — ${status.target}` : '';
+ if (status.state === 'disabled') return `${status.id}: disabled${target}`;
+ if (status.state === 'failed') return `${status.id}: failed — ${status.error ?? 'unknown error'}${target}`;
+ if (status.state === 'connecting') return `${status.id}: connecting${target}`;
+ const allowed = status.tools.filter((tool) => tool.allowed && !tool.skipped).length;
+ const prefix = status.state === 'reconnecting' ? `reconnecting (${status.error ?? 'connection lost'})` : 'connected';
+ return `${status.id}: ${prefix}, ${status.toolCount} tools, ${allowed} allowed${target}`;
+}
+
+export function formatToolLines(status: McpServerStatus): string[] {
+ if (!status.tools.length) return ['(no tools reported)'];
+ return status.tools.map((tool) => {
+ const state = tool.skipped
+ ? `skipped: ${tool.skipped}`
+ : tool.allowed
+ ? tool.autoApprove
+ ? 'allowed, auto-approve'
+ : 'allowed'
+ : 'hidden';
+ return `${tool.name} → ${tool.exposedName} (${state})`;
+ });
+}
+
+export function formatMcpChatStatus(statuses: McpServerStatus[], args: string): string {
+ if (!statuses.length) {
+ return 'No MCP servers configured. Add one from the terminal with `mercury mcp add`.';
+ }
+ const [sub, id] = args.split(/\s+/).filter(Boolean);
+ if (sub === 'tools') {
+ const status = statuses.find((s) => s.id === id);
+ if (!id || !status) return `Usage: /mcp tools <server>. Servers: ${statuses.map((s) => s.id).join(', ')}`;
+ return [`**${status.id}** tools:`, '', ...formatToolLines(status).map((line) => `• ${line}`)].join('\n');
+ }
+ return ['**MCP servers:**', '', ...statuses.map((status) => `• ${formatStatusLine(status)}`), '', 'Details: /mcp tools <server>'].join('\n');
+}
diff --git a/src/capabilities/mcp/config.test.ts b/src/capabilities/mcp/config.test.ts
new file mode 100644
index 00000000..a220d11e
--- /dev/null
+++ b/src/capabilities/mcp/config.test.ts
@@ -0,0 +1,145 @@
+import { describe, expect, it } from 'vitest';
+import { redactSecrets } from '../../utils/redact.js';
+import { resolveSecrets, validateMcpConfig } from './config.js';
+
+const join = (...parts: string[]) => parts.join('');
+
+describe('validateMcpConfig', () => {
+ it('treats a missing section as no servers', () => {
+ expect(validateMcpConfig(undefined)).toEqual({ servers: {}, problems: [], warnings: [] });
+ expect(validateMcpConfig({})).toEqual({ servers: {}, problems: [], warnings: [] });
+ });
+
+ it('accepts stdio and http servers', () => {
+ const result = validateMcpConfig({
+ servers: {
+ github: {
+ transport: 'stdio',
+ command: 'npx',
+ args: ['-y', 'server-github'],
+ env: { GITHUB_TOKEN: '${env:GITHUB_TOKEN}' },
+ tools: { allow: ['search_issues'], autoApprove: ['search_issues'] },
+ },
+ docs: {
+ transport: 'http',
+ url: 'https://mcp.example.com/mcp',
+ headers: { Authorization: 'Bearer ${env:DOCS_TOKEN}' },
+ enabled: false,
+ },
+ },
+ });
+ expect(result.problems).toEqual([]);
+ expect(result.warnings).toEqual([]);
+ expect(Object.keys(result.servers)).toEqual(['github', 'docs']);
+ });
+
+ it('drops invalid servers with a reason and keeps the rest', () => {
+ const result = validateMcpConfig({
+ servers: {
+ Bad_Id: { transport: 'stdio', command: 'x' },
+ nocommand: { transport: 'stdio' },
+ ftp: { transport: 'http', url: 'ftp://example.com/mcp' },
+ typo: { transport: 'stdio', command: 'x', comand: 'y' },
+ unknown: { transport: 'sse', url: 'https://example.com' },
+ good: { transport: 'stdio', command: 'node' },
+ },
+ });
+ expect(Object.keys(result.servers)).toEqual(['good']);
+ expect(result.problems).toHaveLength(5);
+ expect(result.problems[0]).toMatch(/^mcp\.servers\.Bad_Id: server id must match/);
+ expect(result.problems[1]).toMatch(/^mcp\.servers\.nocommand\.command: /);
+ expect(result.problems[2]).toMatch(/^mcp\.servers\.ftp\.url: url must use http or https/);
+ expect(result.problems[3]).toMatch(/^mcp\.servers\.typo: /);
+ expect(result.problems[4]).toMatch(/^mcp\.servers\.unknown\.transport: /);
+ });
+
+ it('rejects a non-mapping section', () => {
+ expect(validateMcpConfig('nope').problems).toEqual(['mcp: expected a mapping with a "servers" key']);
+ expect(validateMcpConfig({ servers: [] }).problems).toEqual([
+ 'mcp.servers: expected a mapping of server id to server settings',
+ ]);
+ });
+
+ it('warns about literal secrets in env and headers', () => {
+ const result = validateMcpConfig({
+ servers: {
+ gh: {
+ transport: 'stdio',
+ command: 'npx',
+ env: { GITHUB_TOKEN: join('ghp_', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '1234') },
+ },
+ docs: {
+ transport: 'http',
+ url: 'https://mcp.example.com/mcp',
+ headers: { Authorization: join('Bearer ', 'abcdefghijklmnopqrstuvwxyz0123456789') },
+ },
+ },
+ });
+ expect(result.warnings).toEqual([
+ 'mcp.servers.gh.env.GITHUB_TOKEN looks like a literal secret; use "${env:NAME}" and keep the value in .env',
+ 'mcp.servers.docs.headers.Authorization looks like a literal secret; use "${env:NAME}" and keep the value in .env',
+ ]);
+ });
+});
+
+describe('Mercury\'s own keys', () => {
+ it('warns when a server is handed one of Mercury\'s provider keys, never for its own token', () => {
+ const result = validateMcpConfig({
+ servers: {
+ docs: { transport: 'http', url: 'https://mcp.example.com/mcp', headers: { Authorization: 'Bearer ${env:ANTHROPIC_API_KEY}' } },
+ gh: { transport: 'stdio', command: 'npx', env: { GITHUB_TOKEN: '${env:GITHUB_TOKEN}' } },
+ },
+ });
+ expect(result.warnings).toEqual([
+ 'mcp.servers.docs is given ANTHROPIC_API_KEY, one of Mercury\'s own keys; the server "docs" will see it. Use a separate key unless you mean this.',
+ ]);
+ });
+});
+
+describe('autoApprove warnings', () => {
+ it('warns when an auto-approved tool is not allowed or is denied', () => {
+ const result = validateMcpConfig({
+ servers: {
+ hidden: { transport: 'stdio', command: 'x', tools: { autoApprove: ['search'] } },
+ denied: { transport: 'stdio', command: 'x', tools: { allow: ['*'], deny: ['search'], autoApprove: ['search'] } },
+ fine: { transport: 'stdio', command: 'x', tools: { allow: ['search'], autoApprove: ['search'] } },
+ wildcard: { transport: 'stdio', command: 'x', tools: { allow: ['*'], autoApprove: ['search'] } },
+ },
+ });
+ expect(result.warnings).toEqual([
+ `mcp.servers.hidden.tools.autoApprove: "search" is not allowed, so the agent can't see it; add it to tools.allow`,
+ `mcp.servers.denied.tools.autoApprove: "search" is in tools.deny, so the agent can't see it; remove it from tools.deny`,
+ ]);
+ });
+});
+
+describe('resolveSecrets', () => {
+ it('expands env references in args, env and headers and registers the values', () => {
+ const token = join('resolved-token-', 'value-0001');
+ const resolved = resolveSecrets(
+ {
+ transport: 'stdio',
+ command: 'node',
+ args: ['--token=${env:MCP_T}'],
+ env: { TOKEN: '${env:MCP_T}', PLAIN: 'yes' },
+ headers: { Authorization: 'Bearer ${env:MCP_T}' },
+ },
+ { MCP_T: token },
+ );
+ expect(resolved).toEqual({
+ args: [`--token=${token}`],
+ env: { TOKEN: token, PLAIN: 'yes' },
+ headers: { Authorization: `Bearer ${token}` },
+ });
+ expect(redactSecrets(`leak ${token}`)).toBe('leak ****');
+ });
+
+ it('fails when a referenced variable is missing or empty', () => {
+ expect(() => resolveSecrets({ transport: 'stdio', command: 'x', env: { A: '${env:MISSING_ONE}' } }, {})).toThrow(
+ 'env MISSING_ONE is not set',
+ );
+ expect(() => resolveSecrets({ transport: 'stdio', command: 'x', args: ['${env:EMPTY}'] }, { EMPTY: '' })).toThrow(
+ 'env EMPTY is not set',
+ );
+ });
+});
diff --git a/src/capabilities/mcp/config.ts b/src/capabilities/mcp/config.ts
new file mode 100644
index 00000000..07718589
--- /dev/null
+++ b/src/capabilities/mcp/config.ts
@@ -0,0 +1,169 @@
+import { z } from 'zod';
+import { redactSecrets, registerSecretValue } from '../../utils/redact.js';
+import type { McpServerConfig } from './types.js';
+
+export const SERVER_ID_PATTERN = /^[a-z][a-z0-9-]{0,23}$/;
+
+const ENV_REF = /\$\{env:([A-Za-z_][A-Za-z0-9_]*)\}/g;
+
+const toolNames = z.array(z.string().min(1)).optional();
+
+const shared = {
+ enabled: z.boolean().optional(),
+ timeoutMs: z.number().int().positive().max(600_000).optional(),
+ tools: z
+ .object({ allow: toolNames, deny: toolNames, autoApprove: toolNames })
+ .strict()
+ .optional(),
+};
+
+const stdioServer = z
+ .object({
+ transport: z.literal('stdio'),
+ command: z.string().min(1),
+ args: z.array(z.string()).optional(),
+ env: z.record(z.string()).optional(),
+ cwd: z.string().min(1).optional(),
+ ...shared,
+ })
+ .strict();
+
+const httpServer = z
+ .object({
+ transport: z.literal('http'),
+ url: z
+ .string()
+ .url()
+ .refine((value) => /^https?:\/\//i.test(value), 'url must use http or https'),
+ headers: z.record(z.string()).optional(),
+ allowPrivate: z.boolean().optional(),
+ ...shared,
+ })
+ .strict();
+
+const serverSchema = z.discriminatedUnion('transport', [stdioServer, httpServer]);
+
+export interface McpConfigValidation {
+ servers: Record<string, McpServerConfig>;
+ problems: string[];
+ warnings: string[];
+}
+
+function formatIssue(id: string, issue: z.ZodIssue): string {
+ const path = issue.path.length ? `.${issue.path.join('.')}` : '';
+ return `mcp.servers.${id}${path}: ${issue.message}`;
+}
+
+function literalSecretWarnings(id: string, field: 'env' | 'headers', values: Record<string, string> | undefined): string[] {
+ if (!values) return [];
+ const warnings: string[] = [];
+ for (const [key, value] of Object.entries(values)) {
+ const withoutRefs = value.replace(ENV_REF, '');
+ if (withoutRefs !== value && !withoutRefs.trim()) continue;
+ if (redactSecrets(withoutRefs) !== withoutRefs) {
+ warnings.push(`mcp.servers.${id}.${field}.${key} looks like a literal secret; use "\${env:NAME}" and keep the value in .env`);
+ }
+ }
+ return warnings;
+}
+
+/**
+ * Mercury's own credentials. `${env:NAME}` can read any variable, so a server
+ * config naming one of these would hand it to a third-party server: allowed
+ * (it may be deliberate), but always called out.
+ */
+const MERCURY_OWN_SECRETS = new Set([
+ 'AIMLAPI_API_KEY', 'ANTHROPIC_API_KEY', 'ATLASCLOUD_API_KEY', 'BOTS_WEBHOOK_SECRET', 'DEEPSEEK_API_KEY',
+ 'DISCORD_BOT_TOKEN', 'GEMINI_API_KEY', 'GOOGLE_API_KEY', 'GROK_API_KEY', 'LITELLM_API_KEY', 'LM_STUDIO_API_KEY',
+ 'MERCURY_CLOUD_ACCESS_KEY', 'MERCURY_CLOUD_AGENT_API_KEY', 'MERCURY_CLOUD_REFRESH_TOKEN', 'MIMO_API_KEY',
+ 'MIMO_TOKEN_PLAN_API_KEY', 'OLLAMA_CLOUD_API_KEY', 'OPENAI_API_KEY', 'OPENAI_COMPAT_API_KEY', 'OPENROUTER_API_KEY',
+ 'SLACK_APP_TOKEN', 'SLACK_BOT_TOKEN', 'SPOTIFY_CLIENT_SECRET', 'TELEGRAM_BOT_TOKEN',
+]);
+
+function ownSecretWarnings(id: string, server: McpServerConfig): string[] {
+ const values = [...(server.args ?? []), ...Object.values(server.env ?? {}), ...Object.values(server.headers ?? {})];
+ const named = new Set<string>();
+ for (const value of values) {
+ for (const match of value.matchAll(ENV_REF)) if (MERCURY_OWN_SECRETS.has(match[1])) named.add(match[1]);
+ }
+ return [...named].map((name) => `mcp.servers.${id} is given ${name}, one of Mercury's own keys; the server "${id}" will see it. Use a separate key unless you mean this.`);
+}
+
+function hiddenAutoApproveWarnings(id: string, server: McpServerConfig): string[] {
+ const allow = server.tools?.allow ?? [];
+ const deny = server.tools?.deny ?? [];
+ const prefix = `mcp.servers.${id}.tools.autoApprove`;
+ return (server.tools?.autoApprove ?? []).flatMap((name) => {
+ if (deny.includes(name)) return [`${prefix}: "${name}" is in tools.deny, so the agent can't see it; remove it from tools.deny`];
+ if (allow.includes('*') || allow.includes(name)) return [];
+ return [`${prefix}: "${name}" is not allowed, so the agent can't see it; add it to tools.allow`];
+ });
+}
+
+export function validateMcpConfig(raw: unknown): McpConfigValidation {
+ const result: McpConfigValidation = { servers: {}, problems: [], warnings: [] };
+ if (raw === undefined || raw === null) return result;
+ if (typeof raw !== 'object' || Array.isArray(raw)) {
+ result.problems.push('mcp: expected a mapping with a "servers" key');
+ return result;
+ }
+ const servers = (raw as { servers?: unknown }).servers;
+ if (servers === undefined || servers === null) return result;
+ if (typeof servers !== 'object' || Array.isArray(servers)) {
+ result.problems.push('mcp.servers: expected a mapping of server id to server settings');
+ return result;
+ }
+ for (const [id, value] of Object.entries(servers as Record<string, unknown>)) {
+ if (!SERVER_ID_PATTERN.test(id)) {
+ result.problems.push(`mcp.servers.${id}: server id must match ${SERVER_ID_PATTERN.source}`);
+ continue;
+ }
+ const parsed = serverSchema.safeParse(value);
+ if (!parsed.success) {
+ result.problems.push(formatIssue(id, parsed.error.issues[0]!));
+ continue;
+ }
+ const server = parsed.data as McpServerConfig;
+ result.servers[id] = server;
+ result.warnings.push(
+ ...literalSecretWarnings(id, 'env', server.env),
+ ...literalSecretWarnings(id, 'headers', server.headers),
+ ...hiddenAutoApproveWarnings(id, server),
+ ...ownSecretWarnings(id, server),
+ );
+ }
+ return result;
+}
+
+export interface ResolvedSecrets {
+ args: string[];
+ env: Record<string, string>;
+ headers: Record<string, string>;
+}
+
+function resolveValue(value: string, source: NodeJS.ProcessEnv): string {
+ return value.replace(ENV_REF, (_match, name: string) => {
+ const resolved = source[name];
+ if (resolved === undefined || resolved === '') {
+ throw new Error(`env ${name} is not set`);
+ }
+ registerSecretValue(resolved);
+ return resolved;
+ });
+}
+
+function resolveRecord(values: Record<string, string> | undefined, source: NodeJS.ProcessEnv): Record<string, string> {
+ const out: Record<string, string> = {};
+ for (const [key, value] of Object.entries(values ?? {})) {
+ out[key] = resolveValue(value, source);
+ }
+ return out;
+}
+
+export function resolveSecrets(server: McpServerConfig, source: NodeJS.ProcessEnv = process.env): ResolvedSecrets {
+ return {
+ args: (server.args ?? []).map((arg) => resolveValue(arg, source)),
+ env: resolveRecord(server.env, source),
+ headers: resolveRecord(server.headers, source),
+ };
+}
diff --git a/src/capabilities/mcp/doctor.test.ts b/src/capabilities/mcp/doctor.test.ts
new file mode 100644
index 00000000..0f2ff9ad
--- /dev/null
+++ b/src/capabilities/mcp/doctor.test.ts
@@ -0,0 +1,54 @@
+import { describe, expect, it } from 'vitest';
+import chalk from 'chalk';
+import { fileURLToPath } from 'node:url';
+import { collectMcpReport, formatMcpReport, mcpReportFailed, summarizeMcpConfig } from './doctor.js';
+
+const FIXTURE = fileURLToPath(new URL('./fixtures/mcp-fixture-server.mjs', import.meta.url));
+chalk.level = 0;
+
+describe('mercury doctor --mcp', () => {
+ it('probes enabled servers and reports each state', async () => {
+ const report = await collectMcpReport(
+ {
+ servers: {
+ fx: { transport: 'stdio', command: process.execPath, args: [FIXTURE], tools: { allow: ['echo'] } },
+ nokey: { transport: 'stdio', command: process.execPath, args: [FIXTURE], env: { T: '${env:MCP_DOCTOR_UNSET}' } },
+ off: { transport: 'stdio', command: 'node', enabled: false },
+ Broken: { transport: 'stdio', command: 'node' },
+ },
+ },
+ 5_000,
+ );
+ expect(report.servers.map((s) => [s.id, s.state])).toEqual([
+ ['fx', 'connected'],
+ ['nokey', 'failed'],
+ ['off', 'disabled'],
+ ]);
+ expect(mcpReportFailed(report)).toBe(true);
+
+ const lines = formatMcpReport(report);
+ expect(lines).toContain(' ✓ fx: connected, 8 tools, 1 allowed — node' + (process.platform === 'win32' ? '.exe' : ''));
+ expect(lines).toContain(' ✗ nokey: failed — env MCP_DOCTOR_UNSET is not set — node' + (process.platform === 'win32' ? '.exe' : ''));
+ expect(lines).toContain(' - off: disabled — node');
+ expect(lines.some((line) => line.startsWith(' ✗ mcp.servers.Broken: server id must match'))).toBe(true);
+ }, 30_000);
+
+ it('passes when everything connects and says so when nothing is configured', async () => {
+ const report = await collectMcpReport(undefined);
+ expect(mcpReportFailed(report)).toBe(false);
+ expect(formatMcpReport(report)).toContain(' No MCP servers configured. Add one with `mercury mcp add`.');
+ });
+
+ it('summarizes the configuration without connecting', () => {
+ expect(summarizeMcpConfig(undefined)).toBeNull();
+ expect(
+ summarizeMcpConfig({
+ servers: {
+ a: { transport: 'stdio', command: 'x' },
+ b: { transport: 'stdio', command: 'x', enabled: false },
+ Bad: { transport: 'stdio', command: 'x' },
+ },
+ }),
+ ).toBe('MCP: 2 servers configured (1 enabled, 1 invalid). Check them with `mercury doctor --mcp`.');
+ });
+});
diff --git a/src/capabilities/mcp/doctor.ts b/src/capabilities/mcp/doctor.ts
new file mode 100644
index 00000000..078773dc
--- /dev/null
+++ b/src/capabilities/mcp/doctor.ts
@@ -0,0 +1,78 @@
+import chalk from 'chalk';
+import { formatStatusLine } from './admin.js';
+import { validateMcpConfig } from './config.js';
+import { DEFAULT_CONNECT_TIMEOUT_MS, probeMcpServer } from './manager.js';
+import { describeTarget } from './transport.js';
+import type { McpServerConfig, McpServerStatus } from './types.js';
+
+export interface McpReport {
+ servers: McpServerStatus[];
+ problems: string[];
+ warnings: string[];
+}
+
+function disabledStatus(id: string, server: McpServerConfig): McpServerStatus {
+ return {
+ id,
+ transport: server.transport,
+ enabled: false,
+ state: 'disabled',
+ target: describeTarget(server),
+ toolCount: 0,
+ tools: [],
+ };
+}
+
+export async function collectMcpReport(raw: unknown, timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS): Promise<McpReport> {
+ const validation = validateMcpConfig(raw);
+ const servers = await Promise.all(
+ Object.entries(validation.servers).map(([id, server]) =>
+ server.enabled === false ? disabledStatus(id, server) : probeMcpServer(id, server, timeoutMs),
+ ),
+ );
+ return { servers, problems: validation.problems, warnings: validation.warnings };
+}
+
+export function mcpReportFailed(report: McpReport): boolean {
+ return report.problems.length > 0 || report.servers.some((server) => server.state === 'failed');
+}
+
+export function formatMcpReport(report: McpReport): string[] {
+ const lines: string[] = ['', chalk.bold(' MCP servers')];
+ if (!report.servers.length && !report.problems.length) {
+ lines.push(chalk.dim(' No MCP servers configured. Add one with `mercury mcp add`.'), '');
+ return lines;
+ }
+ for (const server of report.servers) {
+ const line = formatStatusLine(server);
+ if (server.state === 'connected') lines.push(chalk.green(` ✓ ${line}`));
+ else if (server.state === 'disabled') lines.push(chalk.dim(` - ${line}`));
+ else lines.push(chalk.red(` ✗ ${line}`));
+ for (const tool of server.tools.filter((t) => t.skipped)) {
+ lines.push(chalk.yellow(` skipped ${tool.name}: ${tool.skipped}`));
+ }
+ if (server.state === 'failed' && server.stderrTail) {
+ for (const stderrLine of server.stderrTail.trim().split('\n').slice(-10)) {
+ lines.push(chalk.dim(` ${stderrLine}`));
+ }
+ }
+ }
+ for (const problem of report.problems) lines.push(chalk.red(` ✗ ${problem}`));
+ for (const warning of report.warnings) lines.push(chalk.yellow(` ⚠ ${warning}`));
+ lines.push('');
+ return lines;
+}
+
+export function summarizeMcpConfig(raw: unknown): string | null {
+ const { servers, problems } = validateMcpConfig(raw);
+ const total = Object.keys(servers).length;
+ if (!total && !problems.length) return null;
+ const enabled = Object.values(servers).filter((server) => server.enabled !== false).length;
+ const invalid = problems.length ? `, ${problems.length} invalid` : '';
+ return `MCP: ${total} server${total === 1 ? '' : 's'} configured (${enabled} enabled${invalid}). Check them with \`mercury doctor --mcp\`.`;
+}
+
+export async function runMcpDoctor(raw: unknown): Promise<{ lines: string[]; ok: boolean }> {
+ const report = await collectMcpReport(raw);
+ return { lines: formatMcpReport(report), ok: !mcpReportFailed(report) };
+}
diff --git a/src/capabilities/mcp/e2e.test.ts b/src/capabilities/mcp/e2e.test.ts
new file mode 100644
index 00000000..7cf5e7d8
--- /dev/null
+++ b/src/capabilities/mcp/e2e.test.ts
@@ -0,0 +1,310 @@
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { readFileSync, rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import type { Tool } from 'ai';
+
+const home = await vi.hoisted(async () => {
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join: joinPath } = await import('node:path');
+ const dir = mkdtempSync(joinPath(tmpdir(), 'mercury-mcp-e2e-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const { CapabilityRegistry } = await import('../registry.js');
+const { McpManager } = await import('./manager.js');
+const { formatMcpChatStatus, formatServerList, addServer } = await import('./admin.js');
+const { collectMcpReport, formatMcpReport } = await import('./doctor.js');
+const { default: mcpApi, setMcpManager } = await import('../../web/api/mcp.js');
+const { loadConfig, saveConfig } = await import('../../utils/config.js');
+const { logger } = await import('../../utils/logger.js');
+type McpServerConfig = import('./types.js').McpServerConfig;
+type Manager = InstanceType<typeof McpManager>;
+type Registry = InstanceType<typeof CapabilityRegistry>;
+
+const FIXTURE = fileURLToPath(new URL('./fixtures/mcp-fixture-server.mjs', import.meta.url));
+const SENTINEL = ['sk-mcp-sentinel-', 'A1b2C3d4E5f6G7h8J9k0'].join('');
+const cleanups: Array<() => Promise<void> | void> = [];
+
+afterEach(async () => {
+ for (const cleanup of cleanups.splice(0).reverse()) await cleanup();
+});
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+function fixture(extra: Partial<McpServerConfig> = {}): McpServerConfig {
+ return { transport: 'stdio', command: process.execPath, args: [FIXTURE], ...extra };
+}
+
+async function startHttpFixture(
+ env: Record<string, string>,
+ port = 0,
+): Promise<{ url: string; stop: () => Promise<void> }> {
+ const child: ChildProcess = spawn(process.execPath, [FIXTURE, '--http', String(port)], {
+ env: { ...process.env, ...env },
+ stdio: ['ignore', 'pipe', 'ignore'],
+ });
+ cleanups.push(() => {
+ child.kill();
+ });
+ const listening = await new Promise<number>((resolve, reject) => {
+ let buffered = '';
+ child.stdout!.on('data', (chunk: Buffer) => {
+ buffered += chunk.toString();
+ const match = /LISTENING (\d+)/.exec(buffered);
+ if (match) resolve(Number(match[1]));
+ });
+ child.once('exit', (code) => reject(new Error(`fixture exited with ${code}`)));
+ });
+ const stop = () =>
+ new Promise<void>((resolve) => {
+ if (child.exitCode !== null || child.signalCode !== null) return resolve();
+ child.once('exit', () => resolve());
+ child.kill();
+ });
+ return { url: `http://127.0.0.1:${listening}/mcp`, stop };
+}
+
+interface Harness {
+ registry: Registry;
+ manager: Manager;
+ ask: ReturnType<typeof vi.fn>;
+ run: (name: string, input?: Record<string, unknown>) => Promise<unknown>;
+}
+
+async function harness(
+ servers: Record<string, McpServerConfig>,
+ options: { answer?: string; connectTimeoutMs?: number; backoff?: { initialMs?: number; maxMs?: number; maxAttempts?: number } } = {},
+): Promise<Harness> {
+ const registry = new CapabilityRegistry({} as never);
+ registry.registerAll();
+ const ask = vi.fn().mockResolvedValue(options.answer ?? 'no');
+ registry.permissions.onAsk(ask);
+ registry.permissions.setCurrentContext('cli', 'e2e');
+ const manager = new McpManager(servers, {
+ gate: (request) => registry.permissions.checkMcpTool(request),
+ connectTimeoutMs: options.connectTimeoutMs,
+ backoff: options.backoff,
+ });
+ registry.attachMcp(manager);
+ cleanups.push(() => manager.close());
+ await manager.connectAll();
+ const run = async (name: string, input: Record<string, unknown> = {}) => {
+ const tool: Tool | undefined = registry.getTools()[name];
+ if (!tool?.execute) throw new Error(`tool ${name} is not available`);
+ return tool.execute(input, { toolCallId: 'e2e', messages: [] });
+ };
+ return { registry, manager, ask, run };
+}
+
+async function waitFor(check: () => boolean, timeoutMs = 10_000): Promise<void> {
+ const started = Date.now();
+ while (!check()) {
+ if (Date.now() - started > timeoutMs) throw new Error('condition not met in time');
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+}
+
+describe('MCP end to end over stdio', () => {
+ const servers = () => ({
+ fx: fixture({ tools: { allow: ['echo', 'add', 'crash'], autoApprove: ['add', 'crash'] } }),
+ });
+
+ it('exposes only allowed tools next to the built-in ones', async () => {
+ const { registry } = await harness(servers());
+ const names = registry.getToolNames();
+ expect(names).toEqual(expect.arrayContaining(['read_file', 'mcp__fx__echo', 'mcp__fx__add', 'mcp__fx__crash']));
+ expect(names).not.toContain('mcp__fx__fail');
+ expect(names).not.toContain('mcp__fx__read_env');
+ }, 20_000);
+
+ it('asks before a call and runs it on yes', async () => {
+ const { ask, run } = await harness(servers(), { answer: 'yes' });
+ expect(await run('mcp__fx__echo', { text: 'hello' })).toBe('hello');
+ expect(ask).toHaveBeenCalledWith('MCP tool call\nServer: fx\nTool: echo\nArguments:\n{\n "text": "hello"\n}');
+ }, 20_000);
+
+ it('returns a denial to the agent on no', async () => {
+ const { run } = await harness(servers(), { answer: 'no' });
+ expect(await run('mcp__fx__echo', { text: 'hello' })).toBe('Error: User denied MCP tool fx/echo');
+ }, 20_000);
+
+ it('stops asking after "always" for that channel', async () => {
+ const { ask, run } = await harness(servers(), { answer: 'always' });
+ await run('mcp__fx__echo', { text: 'one' });
+ expect(await run('mcp__fx__echo', { text: 'two' })).toBe('two');
+ expect(ask).toHaveBeenCalledTimes(1);
+ }, 20_000);
+
+ it('still asks under Allow All', async () => {
+ const { registry, ask, run } = await harness(servers(), { answer: 'yes' });
+ registry.permissions.setAutoApproveAll(true);
+ await run('mcp__fx__echo', { text: 'x' });
+ expect(ask).toHaveBeenCalledTimes(1);
+ }, 20_000);
+
+ it('runs only auto-approved tools in unattended turns', async () => {
+ const { registry, ask, run } = await harness(servers(), { answer: 'yes' });
+ registry.permissions.setCurrentContext('internal', 'scheduler');
+ registry.permissions.beginTurnGrant();
+ try {
+ expect(await run('mcp__fx__add', { a: 2, b: 3 })).toBe('5');
+ expect(await run('mcp__fx__echo', { text: 'x' })).toBe(
+ 'Error: MCP tool fx/echo needs approval; add "echo" to tools.autoApprove for server "fx" to run it unattended',
+ );
+ } finally {
+ registry.permissions.endTurnGrant();
+ }
+ expect(ask).not.toHaveBeenCalled();
+ }, 20_000);
+
+ it('keeps MCP tools out of plan mode and away from members', async () => {
+ const { registry } = await harness(servers());
+ expect(Object.keys(registry.getPlanTools()).some((name) => name.startsWith('mcp__'))).toBe(false);
+ registry.permissions.setCurrentSenderRole('member');
+ expect(Object.keys(registry.getTools()).some((name) => name.startsWith('mcp__'))).toBe(false);
+ }, 20_000);
+
+ it('recovers when the server process dies mid-session', async () => {
+ const { manager, run } = await harness(servers(), { backoff: { initialMs: 50, maxMs: 200 } });
+ expect(await run('mcp__fx__crash')).toBe('bye');
+ await waitFor(() => manager.status()[0]?.state === 'reconnecting');
+ expect(await run('mcp__fx__add', { a: 1, b: 2 })).toMatch(/^Error: MCP fx\/add failed: server fx is reconnecting/);
+ await waitFor(() => manager.status()[0]?.state === 'connected');
+ expect(await run('mcp__fx__add', { a: 1, b: 2 })).toBe('3');
+ }, 30_000);
+});
+
+describe('MCP end to end over Streamable HTTP', () => {
+ it('blocks a loopback server unless allowPrivate is set', async () => {
+ const { url } = await startHttpFixture({});
+ const blocked = await harness({ web: { transport: 'http', url, tools: { allow: ['*'] } } }, { backoff: { maxAttempts: 0 } });
+ expect(blocked.manager.status()[0]).toMatchObject({ state: 'failed' });
+ expect(blocked.manager.status()[0]?.error).toMatch(/private\/internal address \(SSRF protection\)\. Set allowPrivate: true/);
+ expect(Object.keys(blocked.registry.getTools()).some((name) => name.startsWith('mcp__'))).toBe(false);
+
+ const allowed = await harness(
+ { web: { transport: 'http', url, allowPrivate: true, tools: { allow: ['add'] } } },
+ { answer: 'yes' },
+ );
+ expect(allowed.manager.status()[0]?.state).toBe('connected');
+ expect(await allowed.run('mcp__web__add', { a: 20, b: 22 })).toBe('42');
+ }, 30_000);
+
+ it('marks a server reconnecting when it goes down and recovers when it is back', async () => {
+ const first = await startHttpFixture({});
+ const port = Number(new URL(first.url).port);
+ const { manager, run } = await harness(
+ { web: { transport: 'http', url: first.url, allowPrivate: true, tools: { allow: ['add'], autoApprove: ['add'] } } },
+ { backoff: { initialMs: 50, maxMs: 200, maxAttempts: 100 } },
+ );
+ expect(await run('mcp__web__add', { a: 1, b: 1 })).toBe('2');
+
+ await first.stop();
+ expect(String(await run('mcp__web__add', { a: 1, b: 1 }))).toMatch(/^Error: MCP web\/add failed: /);
+ expect(manager.status()[0]?.state).toBe('reconnecting');
+
+ await startHttpFixture({}, port);
+ await waitFor(() => manager.status()[0]?.state === 'connected', 15_000);
+ expect(await run('mcp__web__add', { a: 20, b: 22 })).toBe('42');
+ }, 40_000);
+});
+
+describe('MCP failure isolation', () => {
+ it('starts with broken servers present and keeps the rest working', async () => {
+ const started = Date.now();
+ const { manager, registry, run } = await harness(
+ {
+ good: fixture({ tools: { allow: ['echo'], autoApprove: ['echo'] } }),
+ missing: { transport: 'stdio', command: 'mercury-no-such-command-xyz', tools: { allow: ['*'] } },
+ hangs: { transport: 'stdio', command: process.execPath, args: ['-e', 'setInterval(() => {}, 1000)'], tools: { allow: ['*'] } },
+ crashes: fixture({ env: { FIXTURE_EXIT_AT_START: '1' }, tools: { allow: ['*'] } }),
+ },
+ { connectTimeoutMs: 4_000, backoff: { maxAttempts: 0 } },
+ );
+ expect(Date.now() - started).toBeLessThan(15_000);
+ expect(registry.getTools().read_file).toBeDefined();
+ expect(Object.keys(registry.getTools()).filter((name) => name.startsWith('mcp__'))).toEqual(['mcp__good__echo']);
+ expect(await run('mcp__good__echo', { text: 'fine' })).toBe('fine');
+ const states = Object.fromEntries(manager.status().map((s) => [s.id, s.state]));
+ expect(states).toEqual({ good: 'connected', missing: 'failed', hangs: 'failed', crashes: 'failed' });
+ }, 40_000);
+});
+
+describe('MCP secrets never leak', () => {
+ const logged: string[] = [];
+
+ beforeAll(() => {
+ process.env.MCP_SENTINEL = SENTINEL;
+ for (const level of ['trace', 'debug', 'info', 'warn', 'error', 'fatal'] as const) {
+ vi.spyOn(logger, level).mockImplementation(((...args: unknown[]) => {
+ logged.push(JSON.stringify(args));
+ }) as never);
+ }
+ });
+
+ afterAll(() => {
+ delete process.env.MCP_SENTINEL;
+ vi.restoreAllMocks();
+ });
+
+ it('keeps the sentinel out of results, status, API, chat, CLI, doctor, logs and YAML', async () => {
+ const { url } = await startHttpFixture({ FIXTURE_REQUIRE_TOKEN: SENTINEL });
+ const servers: Record<string, McpServerConfig> = {
+ echoer: fixture({ env: { TOKEN: '${env:MCP_SENTINEL}' }, tools: { allow: ['read_env'], autoApprove: ['read_env'] } }),
+ leaky: fixture({ env: { FIXTURE_STDERR_SECRET: '${env:MCP_SENTINEL}', FIXTURE_EXIT_AT_START: '1' } }),
+ web: {
+ transport: 'http',
+ url,
+ allowPrivate: true,
+ headers: { Authorization: 'Bearer ${env:MCP_SENTINEL}' },
+ tools: { allow: ['echo'], autoApprove: ['echo'] },
+ },
+ wrongweb: {
+ transport: 'http',
+ url,
+ allowPrivate: true,
+ headers: { Authorization: 'Bearer ${env:MCP_SENTINEL}-wrong' },
+ tools: { allow: ['*'] },
+ },
+ };
+ const { manager, run } = await harness(servers, { backoff: { maxAttempts: 0 } });
+
+ const states = Object.fromEntries(manager.status().map((s) => [s.id, s.state]));
+ expect(states).toEqual({ echoer: 'connected', leaky: 'failed', web: 'connected', wrongweb: 'failed' });
+ expect(manager.status().find((s) => s.id === 'wrongweb')?.error).toMatch(/^HTTP 401 Unauthorized/);
+
+ const result = String(await run('mcp__echoer__read_env', { name: 'TOKEN' }));
+ expect(result).toBe('****');
+ expect(String(await run('mcp__web__echo', { text: `said ${SENTINEL}` }))).toBe('said ****');
+
+ const statusJson = JSON.stringify(manager.status());
+ const leaky = manager.status().find((s) => s.id === 'leaky');
+ expect(leaky?.stderrTail).toContain('starting with token ****');
+
+ setMcpManager(manager);
+ const apiJson = await (await mcpApi.request('/api/mcp')).text();
+ setMcpManager(null);
+
+ const chat = formatMcpChatStatus(manager.status(), '') + formatMcpChatStatus(manager.status(), 'tools echoer');
+
+ const config = loadConfig();
+ for (const [id, server] of Object.entries(servers)) addServer(config, id, server);
+ const cliList = formatServerList(config).join('\n');
+ saveConfig(config);
+ const yaml = readFileSync(join(home, 'mercury.yaml'), 'utf-8');
+ expect(yaml).toContain('${env:MCP_SENTINEL}');
+
+ const doctor = formatMcpReport(await collectMcpReport({ servers }, 10_000)).join('\n');
+ expect(doctor).toContain('starting with token ****');
+
+ const surfaces = { result, statusJson, apiJson, chat, cliList, yaml, doctor, logs: logged.join('\n') };
+ for (const [surface, text] of Object.entries(surfaces)) {
+ expect(text.includes(SENTINEL), `sentinel leaked into ${surface}`).toBe(false);
+ }
+ expect(logged.length).toBeGreaterThan(0);
+ }, 60_000);
+});
diff --git a/src/capabilities/mcp/fixtures/mcp-fixture-server.mjs b/src/capabilities/mcp/fixtures/mcp-fixture-server.mjs
new file mode 100644
index 00000000..4b453b86
--- /dev/null
+++ b/src/capabilities/mcp/fixtures/mcp-fixture-server.mjs
@@ -0,0 +1,173 @@
+import { createServer } from 'node:http';
+import { createInterface } from 'node:readline';
+import process from 'node:process';
+import { setTimeout } from 'node:timers';
+
+const TINY_PNG =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=';
+
+const tools = [
+ {
+ name: 'echo',
+ description: 'Echo the given text back.',
+ inputSchema: { type: 'object', properties: { text: { type: 'string' } }, required: ['text'] },
+ },
+ {
+ name: 'add',
+ description: 'Add two numbers.',
+ inputSchema: {
+ type: 'object',
+ properties: { a: { type: 'number' }, b: { type: 'number' } },
+ required: ['a', 'b'],
+ },
+ },
+ {
+ name: 'big',
+ description: 'Return a long text result.',
+ inputSchema: { type: 'object', properties: { size: { type: 'number' } } },
+ },
+ {
+ name: 'image',
+ description: 'Return a 1x1 PNG and a caption.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'read_env',
+ description: 'Return the value of an environment variable visible to the server.',
+ inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
+ },
+ {
+ name: 'fail',
+ description: 'Always return an error result.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'crash',
+ description: 'Reply, then exit the server process.',
+ inputSchema: { type: 'object', properties: {} },
+ },
+ {
+ name: 'add_tool',
+ description: 'Register an extra tool and announce tools/list_changed.',
+ inputSchema: { type: 'object', properties: { name: { type: 'string' } }, required: ['name'] },
+ },
+];
+
+const text = (t) => ({ content: [{ type: 'text', text: t }] });
+
+function callTool(name, args, notify) {
+ switch (name) {
+ case 'echo':
+ return text(String(args.text));
+ case 'add':
+ return text(String(Number(args.a) + Number(args.b)));
+ case 'big':
+ return text('x'.repeat(Number(args.size) || 100_000));
+ case 'image':
+ return {
+ content: [
+ { type: 'text', text: 'a pixel' },
+ { type: 'image', data: TINY_PNG, mimeType: 'image/png' },
+ ],
+ };
+ case 'read_env':
+ return text(process.env[String(args.name)] ?? '(unset)');
+ case 'fail':
+ return { content: [{ type: 'text', text: 'it failed' }], isError: true };
+ case 'crash':
+ setTimeout(() => process.exit(1), 20);
+ return text('bye');
+ case 'add_tool':
+ tools.push({
+ name: String(args.name),
+ description: 'Added at runtime.',
+ inputSchema: { type: 'object', properties: {} },
+ });
+ notify({ jsonrpc: '2.0', method: 'notifications/tools/list_changed' });
+ return text('added');
+ default:
+ return null;
+ }
+}
+
+function handle(msg, notify) {
+ if (msg.id === undefined || msg.id === null) return null;
+ const ok = (result) => ({ jsonrpc: '2.0', id: msg.id, result });
+ const err = (code, message) => ({ jsonrpc: '2.0', id: msg.id, error: { code, message } });
+ switch (msg.method) {
+ case 'initialize':
+ return ok({
+ protocolVersion: msg.params?.protocolVersion ?? '2025-06-18',
+ capabilities: { tools: { listChanged: true } },
+ serverInfo: { name: 'mercury-fixture', version: '1.0.0' },
+ });
+ case 'ping':
+ return ok({});
+ case 'tools/list':
+ if (process.env.FIXTURE_EXIT_AFTER_LIST) setTimeout(() => process.exit(1), 20);
+ return ok({ tools });
+ case 'tools/call': {
+ const result = callTool(msg.params?.name, msg.params?.arguments ?? {}, notify);
+ return result ? ok(result) : err(-32602, `Unknown tool: ${msg.params?.name}`);
+ }
+ default:
+ return err(-32601, `Method not found: ${msg.method}`);
+ }
+}
+
+if (process.env.FIXTURE_STDERR_SECRET) {
+ process.stderr.write(`starting with token ${process.env.FIXTURE_STDERR_SECRET}\n`);
+}
+
+const httpIndex = process.argv.indexOf('--http');
+if (process.env.FIXTURE_EXIT_AT_START) {
+ process.exitCode = 3;
+} else if (httpIndex !== -1) {
+ const port = Number(process.argv[httpIndex + 1] ?? 0);
+ const server = createServer((req, res) => {
+ if (req.method !== 'POST') {
+ res.writeHead(405).end();
+ return;
+ }
+ const auth = process.env.FIXTURE_REQUIRE_TOKEN;
+ if (auth && req.headers.authorization !== `Bearer ${auth}`) {
+ res.writeHead(401).end();
+ return;
+ }
+ let body = '';
+ req.on('data', (c) => (body += c));
+ req.on('end', () => {
+ let msg;
+ try {
+ msg = JSON.parse(body);
+ } catch {
+ res.writeHead(400).end();
+ return;
+ }
+ const reply = handle(msg, () => {});
+ if (!reply) {
+ res.writeHead(202).end();
+ return;
+ }
+ res.writeHead(200, { 'content-type': 'application/json' }).end(JSON.stringify(reply));
+ });
+ });
+ server.listen(port, '127.0.0.1', () => {
+ process.stdout.write(`LISTENING ${server.address().port}\n`);
+ });
+} else {
+ const send = (m) => process.stdout.write(JSON.stringify(m) + '\n');
+ const rl = createInterface({ input: process.stdin });
+ rl.on('line', (line) => {
+ if (!line.trim()) return;
+ let msg;
+ try {
+ msg = JSON.parse(line);
+ } catch {
+ return;
+ }
+ const reply = handle(msg, send);
+ if (reply) send(reply);
+ });
+ rl.on('close', () => process.exit(0));
+}
diff --git a/src/capabilities/mcp/gate.test.ts b/src/capabilities/mcp/gate.test.ts
new file mode 100644
index 00000000..484ab74e
--- /dev/null
+++ b/src/capabilities/mcp/gate.test.ts
@@ -0,0 +1,234 @@
+import { afterAll, describe, expect, it, vi } from 'vitest';
+import { rmSync } from 'node:fs';
+import { join } from 'node:path';
+import { tool, zodSchema, type Tool } from 'ai';
+import { z } from 'zod';
+
+const home = await vi.hoisted(async () => {
+ const { mkdtempSync } = await import('node:fs');
+ const { tmpdir } = await import('node:os');
+ const { join: joinPath } = await import('node:path');
+ const dir = mkdtempSync(joinPath(tmpdir(), 'mercury-mcp-gate-'));
+ process.env.MERCURY_HOME = dir;
+ return dir;
+});
+
+const { PermissionManager, formatMcpArgs } = await import('../permissions.js');
+const { CapabilityRegistry } = await import('../registry.js');
+const { filterBotTools } = await import('../../bots/registry-factory.js');
+const { formatToolStep } = await import('../../utils/tool-label.js');
+const { registerSecretValue } = await import('../../utils/redact.js');
+type McpManager = import('./manager.js').McpManager;
+
+afterAll(() => rmSync(home, { recursive: true, force: true }));
+
+const request = (extra: Partial<Parameters<InstanceType<typeof PermissionManager>['checkMcpTool']>[0]> = {}) => ({
+ serverId: 'fx',
+ toolName: 'echo',
+ exposedName: 'mcp__fx__echo',
+ args: { text: 'hi' },
+ autoApprove: false,
+ ...extra,
+});
+
+function manager(answer: string = 'no') {
+ const pm = new PermissionManager();
+ const ask = vi.fn().mockResolvedValue(answer);
+ pm.onAsk(ask);
+ pm.setCurrentContext('cli', 'cli-1');
+ return { pm, ask };
+}
+
+describe('PermissionManager.checkMcpTool', () => {
+ it('runs auto-approved tools without asking, even unattended', async () => {
+ const { pm, ask } = manager();
+ pm.setCurrentContext('internal', 'scheduler');
+ expect(await pm.checkMcpTool(request({ autoApprove: true }))).toEqual({ allowed: true });
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('shows server, tool and arguments, and honours yes and no', async () => {
+ const yes = manager('yes');
+ expect(await yes.pm.checkMcpTool(request())).toEqual({ allowed: true });
+ expect(yes.ask).toHaveBeenCalledWith('MCP tool call\nServer: fx\nTool: echo\nArguments:\n{\n "text": "hi"\n}');
+
+ const no = manager('no');
+ expect(await no.pm.checkMcpTool(request())).toEqual({ allowed: false, reason: 'User denied MCP tool fx/echo' });
+ });
+
+ it('still asks under Allow All', async () => {
+ const { pm, ask } = manager('yes');
+ pm.setAutoApproveAll(true);
+ expect(pm.isAutoApproveAll()).toBe(true);
+ await pm.checkMcpTool(request());
+ expect(ask).toHaveBeenCalledTimes(1);
+ });
+
+ it('remembers "always" for the same channel only', async () => {
+ const { pm, ask } = manager('always');
+ expect((await pm.checkMcpTool(request())).allowed).toBe(true);
+ expect((await pm.checkMcpTool(request({ args: { text: 'again' } }))).allowed).toBe(true);
+ expect(ask).toHaveBeenCalledTimes(1);
+
+ pm.setCurrentContext('cli', 'cli-2');
+ await pm.checkMcpTool(request());
+ expect(ask).toHaveBeenCalledTimes(2);
+
+ await pm.checkMcpTool(request({ toolName: 'add', exposedName: 'mcp__fx__add' }));
+ expect(ask).toHaveBeenCalledTimes(3);
+ });
+
+ it('denies unattended runs, including internal turns with a turn grant', async () => {
+ const { pm, ask } = manager('yes');
+ pm.setCurrentContext('internal', 'scheduler');
+ pm.beginTurnGrant();
+ const result = await pm.checkMcpTool(request());
+ pm.endTurnGrant();
+ expect(result.allowed).toBe(false);
+ expect(result.reason).toBe(
+ 'MCP tool fx/echo needs approval; add "echo" to tools.autoApprove for server "fx" to run it unattended',
+ );
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('denies when nothing can ask, and in fail-closed mode', async () => {
+ const pm = new PermissionManager();
+ pm.setCurrentContext('cli', 'cli-1');
+ expect((await pm.checkMcpTool(request())).allowed).toBe(false);
+
+ const bot = manager('yes');
+ bot.pm.setFailClosed(true);
+ expect(await bot.pm.checkMcpTool(request())).toEqual({
+ allowed: false,
+ reason: 'Fail-closed: MCP tool fx/echo is not in tools.autoApprove',
+ });
+ expect(bot.ask).not.toHaveBeenCalled();
+ });
+
+ it('redacts and truncates the arguments it shows', async () => {
+ const secret = ['gate-secret-', 'value-123'].join('');
+ registerSecretValue(secret);
+ const { pm, ask } = manager('no');
+ await pm.checkMcpTool(request({ args: { token: secret } }));
+ expect(ask.mock.calls[0]?.[0]).not.toContain(secret);
+
+ // Ordinary arguments are shown whole, however many lines.
+ const many = Object.fromEntries(Array.from({ length: 30 }, (_, i) => [`k${i}`, i]));
+ expect(formatMcpArgs(many)).toBe(JSON.stringify(many, null, 2));
+
+ // A long payload keeps its start and its end: nothing hides after a cut.
+ const shown = formatMcpArgs({ note: 'hello', filler: 'x'.repeat(20_000), tail: 'DELETE EVERYTHING' });
+ expect(shown).toContain('"note": "hello"');
+ expect(shown).toContain('DELETE EVERYTHING');
+ expect(shown).toMatch(/characters not shown/);
+ expect(shown.length).toBeLessThan(4000);
+ });
+
+ it('a shell command that changes MCP setup always asks, even under Allow All', async () => {
+ const { changesMcpSetup } = await import('../permissions.js');
+ expect(changesMcpSetup('mercury mcp add evil --stdio sh -y --auto-approve run')).toBe(true);
+ expect(changesMcpSetup('npx mercury-agent mcp enable evil')).toBe(true);
+ expect(changesMcpSetup("sed -i 's/x/y/' ~/.mercury/mercury.yaml")).toBe(true);
+ expect(changesMcpSetup('mercury mcp list')).toBe(false);
+ expect(changesMcpSetup('ls -la')).toBe(false);
+
+ const { pm, ask } = manager('no');
+ pm.setAutoApproveAll(true);
+ const check = await pm.checkShellCommand('mercury mcp add evil --stdio sh -y');
+ expect(check.allowed).toBe(false);
+ expect(ask).toHaveBeenCalledTimes(1);
+ expect(String(ask.mock.calls[0]?.[0])).toMatch(/always asks/);
+ expect((await pm.checkShellCommand('echo hi')).allowed).toBe(true);
+ });
+});
+
+describe('Mercury config file protection', () => {
+ function writer(answer: string) {
+ const { pm, ask } = manager(answer);
+ pm.getManifest().capabilities.filesystem.scopes = [{ path: home, read: true, write: true }];
+ pm.setAutoApproveAll(true);
+ return { pm, ask };
+ }
+
+ it('asks before writing mercury.yaml, .env or permissions.yaml even under Allow All', async () => {
+ for (const file of ['mercury.yaml', '.env', 'permissions.yaml']) {
+ const { pm, ask } = writer('no');
+ const result = await pm.checkFsAccess(join(home, file), 'write');
+ expect(result.allowed).toBe(false);
+ expect(ask.mock.calls[0]?.[0]).toMatch(/^Write to Mercury config file: /);
+ }
+ const { pm } = writer('yes');
+ expect((await pm.checkFsAccess(join(home, 'mercury.yaml'), 'write')).allowed).toBe(true);
+ });
+
+ it('denies config writes when nobody can confirm', async () => {
+ const { pm, ask } = writer('yes');
+ pm.setCurrentContext('internal', 'scheduler');
+ const result = await pm.checkFsAccess(join(home, 'mercury.yaml'), 'write');
+ expect(result.allowed).toBe(false);
+ expect(result.reason).toMatch(/is a Mercury config file/);
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('leaves other files in the same folder alone', async () => {
+ const { pm, ask } = writer('no');
+ expect((await pm.checkFsAccess(join(home, 'notes.txt'), 'write')).allowed).toBe(true);
+ expect(ask).not.toHaveBeenCalled();
+ });
+
+ it('matches config files case-insensitively on macOS', async () => {
+ const platform = Object.getOwnPropertyDescriptor(process, 'platform')!;
+ Object.defineProperty(process, 'platform', { value: 'darwin' });
+ try {
+ const { pm, ask } = writer('no');
+ const result = await pm.checkFsAccess(join(home, 'MERCURY.YAML'), 'write');
+ expect(result.allowed).toBe(false);
+ expect(ask.mock.calls[0]?.[0]).toMatch(/^Write to Mercury config file: /);
+ } finally {
+ Object.defineProperty(process, 'platform', platform);
+ }
+ });
+});
+
+describe('MCP tools in the registry and filters', () => {
+ const echo: Tool = tool({
+ description: 'echo',
+ inputSchema: zodSchema(z.object({})),
+ execute: async () => 'ok',
+ });
+ const fakeMcp = { getTools: () => ({ mcp__fx__echo: echo }) } as unknown as McpManager;
+
+ it('adds MCP tools to the tool set and names', () => {
+ const registry = new CapabilityRegistry({} as never);
+ registry.registerAll();
+ registry.attachMcp(fakeMcp);
+ expect(registry.getTools().mcp__fx__echo).toBe(echo);
+ expect(registry.getToolNames()).toContain('mcp__fx__echo');
+ expect(registry.getMcpManager()).toBe(fakeMcp);
+ });
+
+ it('hides MCP tools from members and from plan mode', () => {
+ const registry = new CapabilityRegistry({} as never);
+ registry.registerAll();
+ registry.attachMcp(fakeMcp);
+ expect(registry.getPlanTools().mcp__fx__echo).toBeUndefined();
+ registry.permissions.setCurrentSenderRole('member');
+ expect(registry.getTools().mcp__fx__echo).toBeUndefined();
+ registry.permissions.setCurrentSenderRole('admin');
+ expect(registry.getTools().mcp__fx__echo).toBe(echo);
+ });
+
+ it('never gives bots MCP tools, even when allow-listed', () => {
+ const filtered = filterBotTools(
+ { read_file: 1, mcp__fx__echo: 2 },
+ {} as never,
+ { tools: { allow: ['read_file', 'mcp__fx__echo'], deny: [] } } as never,
+ );
+ expect(Object.keys(filtered)).toEqual(['read_file']);
+ });
+
+ it('labels MCP tool steps by server and tool', () => {
+ expect(formatToolStep('mcp__github__search_issues', {})).toBe('🔌 github › search_issues');
+ expect(formatToolStep('some_unknown_tool', {})).toBe('some_unknown_tool');
+ });
+});
diff --git a/src/capabilities/mcp/index.ts b/src/capabilities/mcp/index.ts
new file mode 100644
index 00000000..79dda35e
--- /dev/null
+++ b/src/capabilities/mcp/index.ts
@@ -0,0 +1,7 @@
+export * from './types.js';
+export { validateMcpConfig, resolveSecrets, SERVER_ID_PATTERN } from './config.js';
+export type { McpConfigValidation, ResolvedSecrets } from './config.js';
+export { exposedToolName, isMcpToolName, MCP_TOOL_PREFIX, MAX_TOOL_NAME_LENGTH } from './naming.js';
+export { McpManager, probeMcpServer, isToolAllowed, isToolAutoApproved } from './manager.js';
+export type { McpManagerOptions, McpBackoff } from './manager.js';
+export { callResultToText, MAX_RESULT_CHARS } from './result.js';
diff --git a/src/capabilities/mcp/manager.test.ts b/src/capabilities/mcp/manager.test.ts
new file mode 100644
index 00000000..b06f0bde
--- /dev/null
+++ b/src/capabilities/mcp/manager.test.ts
@@ -0,0 +1,198 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { fileURLToPath } from 'node:url';
+import type { Tool } from 'ai';
+import { McpManager, probeMcpServer, type McpManagerOptions } from './manager.js';
+import type { McpGate, McpServerConfig } from './types.js';
+
+const FIXTURE = fileURLToPath(new URL('./fixtures/mcp-fixture-server.mjs', import.meta.url));
+const allowAll: McpGate = async () => ({ allowed: true });
+const managers: McpManager[] = [];
+
+function fixture(extra: Partial<McpServerConfig> = {}): McpServerConfig {
+ return { transport: 'stdio', command: process.execPath, args: [FIXTURE], ...extra };
+}
+
+function manager(servers: Record<string, McpServerConfig>, options: Partial<McpManagerOptions> = {}): McpManager {
+ const created = new McpManager(servers, { gate: allowAll, ...options });
+ managers.push(created);
+ return created;
+}
+
+async function run(tool: Tool | undefined, input: Record<string, unknown>): Promise<unknown> {
+ expect(tool?.execute).toBeTypeOf('function');
+ return tool!.execute!(input, { toolCallId: 'call-1', messages: [] });
+}
+
+async function waitFor(check: () => boolean, timeoutMs = 10_000): Promise<void> {
+ const started = Date.now();
+ while (!check()) {
+ if (Date.now() - started > timeoutMs) throw new Error('condition not met in time');
+ await new Promise((resolve) => setTimeout(resolve, 25));
+ }
+}
+
+afterEach(async () => {
+ await Promise.allSettled(managers.splice(0).map((m) => m.close()));
+});
+
+describe('McpManager', () => {
+ it('exposes only allowed tools, with deny winning over allow', async () => {
+ const m = manager({
+ fx: fixture({ tools: { allow: ['*'], deny: ['fail', 'crash', 'add_tool'] } }),
+ picky: fixture({ tools: { allow: ['echo'] } }),
+ off: fixture({ enabled: false, tools: { allow: ['*'] } }),
+ });
+ await m.connectAll();
+ const names = Object.keys(m.getTools()).sort();
+ expect(names).toEqual([
+ 'mcp__fx__add',
+ 'mcp__fx__big',
+ 'mcp__fx__echo',
+ 'mcp__fx__image',
+ 'mcp__fx__read_env',
+ 'mcp__picky__echo',
+ ]);
+ const status = Object.fromEntries(m.status().map((s) => [s.id, s]));
+ expect(status.fx?.state).toBe('connected');
+ expect(status.fx?.toolCount).toBe(8);
+ expect(status.fx?.target).toMatch(/node/i);
+ expect(status.off?.state).toBe('disabled');
+ expect(status.off?.enabled).toBe(false);
+ }, 20_000);
+
+ it('runs tools through the gate and converts results to text', async () => {
+ const gate = vi.fn<McpGate>(async (request) =>
+ request.toolName === 'add' ? { allowed: true } : { allowed: false, reason: 'User denied: echo' },
+ );
+ const m = manager({ fx: fixture({ tools: { allow: ['add', 'echo', 'image'], autoApprove: ['add'] } }) }, { gate });
+ await m.connectAll();
+ const tools = m.getTools();
+
+ expect(await run(tools.mcp__fx__add, { a: 2, b: 3 })).toBe('5');
+ expect(gate).toHaveBeenCalledWith({
+ serverId: 'fx',
+ toolName: 'add',
+ exposedName: 'mcp__fx__add',
+ args: { a: 2, b: 3 },
+ autoApprove: true,
+ });
+ expect(await run(tools.mcp__fx__echo, { text: 'hi' })).toBe('Error: User denied: echo');
+ expect(m.isAutoApproved('mcp__fx__add')).toBe(true);
+ expect(m.isAutoApproved('mcp__fx__echo')).toBe(false);
+ }, 20_000);
+
+ it('returns an error string when the gate throws', async () => {
+ const m = manager(
+ { fx: fixture({ tools: { allow: ['echo'] } }) },
+ { gate: async () => Promise.reject(new Error('handler crashed')) },
+ );
+ await m.connectAll();
+ expect(await run(m.getTools().mcp__fx__echo, { text: 'x' })).toBe(
+ 'Error: permission check for MCP fx/echo failed: handler crashed',
+ );
+ }, 20_000);
+
+ it('keeps healthy servers working when others fail', async () => {
+ const m = manager(
+ {
+ good: fixture({ tools: { allow: ['echo'] } }),
+ missing: { transport: 'stdio', command: 'mercury-no-such-command-xyz', tools: { allow: ['*'] } },
+ nosecret: fixture({ env: { TOKEN: '${env:MCP_TEST_UNSET_VARIABLE}' }, tools: { allow: ['*'] } }),
+ hangs: {
+ transport: 'stdio',
+ command: process.execPath,
+ args: ['-e', 'setInterval(() => {}, 1000)'],
+ tools: { allow: ['*'] },
+ },
+ },
+ { connectTimeoutMs: 4_000, backoff: { maxAttempts: 0 } },
+ );
+ const started = Date.now();
+ await m.connectAll();
+ expect(Date.now() - started).toBeLessThan(15_000);
+
+ expect(Object.keys(m.getTools())).toEqual(['mcp__good__echo']);
+ expect(await run(m.getTools().mcp__good__echo, { text: 'still here' })).toBe('still here');
+
+ const status = Object.fromEntries(m.status().map((s) => [s.id, s]));
+ expect(status.good?.state).toBe('connected');
+ expect(status.missing?.state).toBe('failed');
+ expect(status.nosecret?.state).toBe('failed');
+ expect(status.nosecret?.error).toBe('env MCP_TEST_UNSET_VARIABLE is not set');
+ expect(status.hangs?.state).toBe('failed');
+ expect(status.hangs?.error).toMatch(/timed out after 4000 ms/);
+ }, 40_000);
+
+ it('reconnects after the server process dies', async () => {
+ const m = manager(
+ { fx: fixture({ tools: { allow: ['add', 'crash'] } }) },
+ { backoff: { initialMs: 50, maxMs: 200 } },
+ );
+ await m.connectAll();
+ expect(await run(m.getTools().mcp__fx__crash, {})).toBe('bye');
+
+ await waitFor(() => m.status()[0]?.state === 'reconnecting');
+ const during = await run(m.getTools().mcp__fx__add, { a: 1, b: 1 });
+ expect(during).toMatch(/^Error: MCP fx\/add failed: server fx is reconnecting/);
+
+ await waitFor(() => m.status()[0]?.state === 'connected');
+ expect(await run(m.getTools().mcp__fx__add, { a: 1, b: 1 })).toBe('2');
+ }, 30_000);
+
+ it('gives up on a server that dies right after every connect', async () => {
+ const m = manager(
+ { fx: fixture({ env: { FIXTURE_EXIT_AFTER_LIST: '1' }, tools: { allow: ['*'] } }) },
+ { backoff: { initialMs: 20, maxMs: 20, maxAttempts: 3 } },
+ );
+ await m.connectAll();
+ await waitFor(() => m.status()[0]?.state === 'failed', 15_000);
+ expect(m.status()[0]?.error).toMatch(/gave up after 3 attempts/);
+ expect(m.getTools()).toEqual({});
+ }, 30_000);
+
+ it('picks up tools announced through tools/list_changed', async () => {
+ const onToolsChanged = vi.fn();
+ const m = manager({ fx: fixture({ tools: { allow: ['*'] } }) }, { onToolsChanged });
+ await m.connectAll();
+ expect(m.getTools().mcp__fx__late_tool).toBeUndefined();
+
+ await run(m.getTools().mcp__fx__add_tool, { name: 'late_tool' });
+ await waitFor(() => m.getTools().mcp__fx__late_tool !== undefined);
+ expect(onToolsChanged).toHaveBeenCalled();
+ }, 20_000);
+
+ it('stops reconnecting once closed', async () => {
+ const m = manager({ fx: fixture({ tools: { allow: ['crash'] } }) }, { backoff: { initialMs: 50, maxMs: 50 } });
+ await m.connectAll();
+ await run(m.getTools().mcp__fx__crash, {});
+ await m.close();
+ await new Promise((resolve) => setTimeout(resolve, 300));
+ expect(m.status()[0]).toMatchObject({ state: 'failed', error: 'manager closed', toolCount: 0 });
+ expect(m.getTools()).toEqual({});
+ }, 20_000);
+});
+
+describe('probeMcpServer', () => {
+ it('reports tools with their allow and skip state', async () => {
+ const status = await probeMcpServer('fx', fixture({ tools: { allow: ['echo'], autoApprove: ['echo'] } }));
+ expect(status.state).toBe('connected');
+ expect(status.tools.find((t) => t.name === 'echo')).toEqual({
+ name: 'echo',
+ exposedName: 'mcp__fx__echo',
+ allowed: true,
+ autoApprove: true,
+ skipped: undefined,
+ });
+ expect(status.tools.find((t) => t.name === 'add')?.allowed).toBe(false);
+ }, 20_000);
+
+ it('reports a failure reason', async () => {
+ const status = await probeMcpServer(
+ 'gone',
+ { transport: 'stdio', command: 'mercury-no-such-command-xyz' },
+ 2_000,
+ );
+ expect(status.state).toBe('failed');
+ expect(status.error).toBeTruthy();
+ }, 20_000);
+});
diff --git a/src/capabilities/mcp/manager.ts b/src/capabilities/mcp/manager.ts
new file mode 100644
index 00000000..b65093b1
--- /dev/null
+++ b/src/capabilities/mcp/manager.ts
@@ -0,0 +1,398 @@
+import type { Schema, Tool } from 'ai';
+import { Client, type Tool as McpTool } from '@modelcontextprotocol/client';
+import { logger } from '../../utils/logger.js';
+import { redactSecrets } from '../../utils/redact.js';
+import { resolveSecrets } from './config.js';
+import { exposedToolName } from './naming.js';
+import { toInputSchema } from './schema.js';
+import { buildMcpTool } from './tool.js';
+import { createTransport, describeTarget } from './transport.js';
+import type { McpCallResultLike } from './result.js';
+import type { McpGate, McpServerConfig, McpServerState, McpServerStatus, McpToolStatus } from './types.js';
+
+export const DEFAULT_CONNECT_TIMEOUT_MS = 15_000;
+export const DEFAULT_CALL_TIMEOUT_MS = 60_000;
+export const CLOSE_TIMEOUT_MS = 3_000;
+
+export interface McpBackoff {
+ initialMs: number;
+ maxMs: number;
+ maxAttempts: number;
+ stableMs: number;
+}
+
+const DEFAULT_BACKOFF: McpBackoff = { initialMs: 1_000, maxMs: 300_000, maxAttempts: 10, stableMs: 60_000 };
+
+export interface McpManagerOptions {
+ gate: McpGate;
+ onToolsChanged?: () => void;
+ connectTimeoutMs?: number;
+ backoff?: Partial<McpBackoff>;
+}
+
+interface DescribedTool {
+ status: McpToolStatus;
+ description?: string;
+ schema?: Schema<Record<string, unknown>>;
+}
+
+interface ToolEntry extends McpToolStatus {
+ tool?: Tool;
+}
+
+interface ServerEntry {
+ id: string;
+ config: McpServerConfig;
+ state: McpServerState;
+ error?: string;
+ client?: Client;
+ stderrTail: () => string;
+ tools: ToolEntry[];
+ attempts: number;
+ connectedAt?: number;
+ generation: number;
+ timer?: ReturnType<typeof setTimeout>;
+}
+
+function clientInfo(): { name: string; version: string } {
+ const version = (globalThis as { __MERCURY_VERSION__?: string }).__MERCURY_VERSION__ ?? '0.0.0';
+ return { name: 'mercury', version };
+}
+
+function errorMessage(err: unknown): string {
+ const data = (err as { data?: { status?: unknown; statusText?: unknown; text?: unknown } } | null)?.data;
+ if (data && typeof data.status === 'number') {
+ const statusText = typeof data.statusText === 'string' && data.statusText ? ` ${data.statusText}` : '';
+ const body = typeof data.text === 'string' && data.text.trim() ? `: ${data.text.trim().slice(0, 200)}` : '';
+ return redactSecrets(`HTTP ${data.status}${statusText}${body}`);
+ }
+ return redactSecrets(err instanceof Error ? err.message : String(err));
+}
+
+const CONNECTION_ERROR_CODES = new Set([
+ 'ECONNREFUSED',
+ 'ECONNRESET',
+ 'ENOTFOUND',
+ 'EAI_AGAIN',
+ 'EHOSTUNREACH',
+ 'ENETUNREACH',
+ 'ETIMEDOUT',
+ 'EPIPE',
+ 'UND_ERR_SOCKET',
+ 'UND_ERR_CONNECT_TIMEOUT',
+]);
+
+function isConnectionError(err: unknown): boolean {
+ let current: unknown = err;
+ for (let depth = 0; depth < 5 && current && typeof current === 'object'; depth++) {
+ const { code, message, cause } = current as { code?: unknown; message?: unknown; cause?: unknown };
+ if (typeof code === 'string' && CONNECTION_ERROR_CODES.has(code)) return true;
+ if (message === 'fetch failed') return true;
+ current = cause;
+ }
+ return false;
+}
+
+export function withTimeout<T>(promise: Promise<T>, ms: number, label: string): Promise<T> {
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const timeout = new Promise<never>((_, reject) => {
+ timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms} ms`)), ms);
+ });
+ return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
+}
+
+async function closeQuietly(client: Client): Promise<void> {
+ try {
+ await withTimeout(client.close(), CLOSE_TIMEOUT_MS, 'close');
+ } catch {
+ return;
+ }
+}
+
+export function isToolAllowed(config: McpServerConfig, toolName: string): boolean {
+ const filter = config.tools ?? {};
+ if (filter.deny?.includes(toolName)) return false;
+ return filter.allow?.includes('*') === true || filter.allow?.includes(toolName) === true;
+}
+
+export function isToolAutoApproved(config: McpServerConfig, toolName: string): boolean {
+ return config.tools?.autoApprove?.includes(toolName) === true;
+}
+
+export function describeTools(serverId: string, config: McpServerConfig, tools: McpTool[]): DescribedTool[] {
+ const taken = new Set<string>();
+ const seen = new Set<string>();
+ const described: DescribedTool[] = [];
+ for (const tool of tools) {
+ if (seen.has(tool.name)) continue;
+ seen.add(tool.name);
+ const exposedName = exposedToolName(serverId, tool.name, taken);
+ taken.add(exposedName);
+ const schema = toInputSchema(tool.inputSchema);
+ described.push({
+ status: {
+ name: tool.name,
+ exposedName,
+ allowed: isToolAllowed(config, tool.name),
+ autoApprove: isToolAutoApproved(config, tool.name),
+ skipped: 'skip' in schema ? schema.skip : undefined,
+ },
+ description: tool.description,
+ schema: 'schema' in schema ? schema.schema : undefined,
+ });
+ }
+ return described;
+}
+
+function baseStatus(id: string, config: McpServerConfig): Omit<McpServerStatus, 'state'> {
+ return {
+ id,
+ transport: config.transport,
+ enabled: config.enabled !== false,
+ target: describeTarget(config),
+ toolCount: 0,
+ tools: [],
+ };
+}
+
+export async function probeMcpServer(
+ id: string,
+ config: McpServerConfig,
+ timeoutMs = DEFAULT_CONNECT_TIMEOUT_MS,
+): Promise<McpServerStatus> {
+ let stderrTail = (): string => '';
+ const client = new Client(clientInfo());
+ try {
+ const created = createTransport(config, resolveSecrets(config));
+ stderrTail = created.stderrTail;
+ await withTimeout(client.connect(created.transport), timeoutMs, 'connect');
+ const { tools } = await withTimeout(client.listTools(), timeoutMs, 'tools/list');
+ const statuses = describeTools(id, config, tools).map((d) => d.status);
+ return { ...baseStatus(id, config), state: 'connected', toolCount: statuses.length, tools: statuses };
+ } catch (err) {
+ return {
+ ...baseStatus(id, config),
+ state: 'failed',
+ error: errorMessage(err),
+ stderrTail: stderrTail() || undefined,
+ };
+ } finally {
+ await closeQuietly(client);
+ }
+}
+
+export class McpManager {
+ private readonly servers = new Map<string, ServerEntry>();
+ private readonly connectTimeoutMs: number;
+ private readonly backoff: McpBackoff;
+ private closed = false;
+
+ constructor(servers: Record<string, McpServerConfig>, private readonly options: McpManagerOptions) {
+ this.connectTimeoutMs = options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS;
+ this.backoff = { ...DEFAULT_BACKOFF, ...options.backoff };
+ for (const [id, config] of Object.entries(servers)) {
+ this.servers.set(id, {
+ id,
+ config,
+ state: config.enabled === false ? 'disabled' : 'connecting',
+ stderrTail: () => '',
+ tools: [],
+ attempts: 0,
+ generation: 0,
+ });
+ }
+ }
+
+ async connectAll(): Promise<void> {
+ const pending = [...this.servers.values()].filter((entry) => entry.state !== 'disabled');
+ await Promise.allSettled(pending.map((entry) => this.connect(entry)));
+ }
+
+ getTools(): Record<string, Tool> {
+ const tools: Record<string, Tool> = {};
+ for (const entry of this.servers.values()) {
+ if (entry.state !== 'connected' && entry.state !== 'reconnecting') continue;
+ for (const tool of entry.tools) {
+ if (tool.tool) tools[tool.exposedName] = tool.tool;
+ }
+ }
+ return tools;
+ }
+
+ isAutoApproved(exposedName: string): boolean {
+ for (const entry of this.servers.values()) {
+ const tool = entry.tools.find((t) => t.exposedName === exposedName);
+ if (tool) return tool.autoApprove;
+ }
+ return false;
+ }
+
+ status(): McpServerStatus[] {
+ return [...this.servers.values()].map((entry) => ({
+ ...baseStatus(entry.id, entry.config),
+ state: entry.state,
+ error: entry.error,
+ toolCount: entry.tools.length,
+ tools: entry.tools.map((tool) => ({
+ name: tool.name,
+ exposedName: tool.exposedName,
+ allowed: tool.allowed,
+ autoApprove: tool.autoApprove,
+ skipped: tool.skipped,
+ })),
+ stderrTail: entry.stderrTail() || undefined,
+ }));
+ }
+
+ async testServer(id: string): Promise<McpServerStatus | undefined> {
+ const entry = this.servers.get(id);
+ return entry ? probeMcpServer(id, entry.config, this.connectTimeoutMs) : undefined;
+ }
+
+ async close(): Promise<void> {
+ this.closed = true;
+ await Promise.allSettled(
+ [...this.servers.values()].map(async (entry) => {
+ if (entry.timer) clearTimeout(entry.timer);
+ entry.timer = undefined;
+ entry.generation++;
+ const client = entry.client;
+ entry.client = undefined;
+ entry.tools = [];
+ if (entry.state !== 'disabled') {
+ entry.state = 'failed';
+ entry.error = 'manager closed';
+ }
+ if (client) await closeQuietly(client);
+ }),
+ );
+ }
+
+ private async connect(entry: ServerEntry): Promise<void> {
+ if (this.closed) return;
+ entry.timer = undefined;
+ const generation = ++entry.generation;
+ let created;
+ try {
+ created = createTransport(entry.config, resolveSecrets(entry.config));
+ } catch (err) {
+ this.fail(entry, errorMessage(err));
+ return;
+ }
+ entry.stderrTail = created.stderrTail;
+ const client = new Client(clientInfo(), {
+ listChanged: {
+ tools: {
+ onChanged: (err, tools) => {
+ if (entry.generation !== generation) return;
+ if (err) {
+ logger.warn({ server: entry.id, err: errorMessage(err) }, 'MCP tool list refresh failed');
+ return;
+ }
+ if (tools) this.applyTools(entry, tools);
+ },
+ },
+ },
+ });
+ let established = false;
+ client.onclose = () => {
+ if (established) this.scheduleReconnect(entry, 'connection closed', generation);
+ };
+ try {
+ await withTimeout(client.connect(created.transport), this.connectTimeoutMs, 'connect');
+ const { tools } = await withTimeout(client.listTools(), this.connectTimeoutMs, 'tools/list');
+ if (entry.generation !== generation || this.closed) {
+ await closeQuietly(client);
+ return;
+ }
+ established = true;
+ entry.client = client;
+ entry.state = 'connected';
+ entry.error = undefined;
+ entry.connectedAt = Date.now();
+ this.applyTools(entry, tools);
+ logger.info({ server: entry.id, tools: entry.tools.length }, 'MCP server connected');
+ } catch (err) {
+ this.scheduleReconnect(entry, errorMessage(err), generation);
+ await closeQuietly(client);
+ }
+ }
+
+ private scheduleReconnect(entry: ServerEntry, reason: string, generation: number): void {
+ if (this.closed || entry.generation !== generation) return;
+ entry.generation++;
+ const client = entry.client;
+ entry.client = undefined;
+ if (client) void closeQuietly(client);
+ entry.error = reason;
+ if (entry.connectedAt !== undefined && Date.now() - entry.connectedAt >= this.backoff.stableMs) entry.attempts = 0;
+ entry.connectedAt = undefined;
+ entry.attempts++;
+ if (entry.attempts > this.backoff.maxAttempts) {
+ this.fail(entry, `${reason} (gave up after ${this.backoff.maxAttempts} attempts)`);
+ return;
+ }
+ entry.state = 'reconnecting';
+ const base = Math.min(this.backoff.maxMs, this.backoff.initialMs * 2 ** (entry.attempts - 1));
+ const delay = Math.round(base * (0.8 + Math.random() * 0.4));
+ logger.warn({ server: entry.id, attempt: entry.attempts, delayMs: delay, reason }, 'MCP server unavailable, retrying');
+ entry.timer = setTimeout(() => void this.connect(entry), delay);
+ entry.timer.unref?.();
+ }
+
+ private fail(entry: ServerEntry, reason: string): void {
+ entry.state = 'failed';
+ entry.error = reason;
+ entry.client = undefined;
+ logger.warn({ server: entry.id, reason }, 'MCP server failed');
+ if (entry.tools.length) {
+ entry.tools = [];
+ this.options.onToolsChanged?.();
+ }
+ }
+
+ private applyTools(entry: ServerEntry, tools: McpTool[]): void {
+ entry.tools = describeTools(entry.id, entry.config, tools).map(({ status, description, schema }) => {
+ if (status.skipped) {
+ logger.warn({ server: entry.id, tool: status.name, reason: status.skipped }, 'MCP tool skipped');
+ }
+ const tool =
+ status.allowed && schema
+ ? buildMcpTool({
+ serverId: entry.id,
+ toolName: status.name,
+ exposedName: status.exposedName,
+ description,
+ inputSchema: schema,
+ autoApprove: status.autoApprove,
+ gate: this.options.gate,
+ call: (name, args, signal) => this.call(entry, name, args, signal),
+ })
+ : undefined;
+ return { ...status, tool };
+ });
+ this.options.onToolsChanged?.();
+ }
+
+ private async call(
+ entry: ServerEntry,
+ toolName: string,
+ args: Record<string, unknown>,
+ signal: AbortSignal | undefined,
+ ): Promise<McpCallResultLike> {
+ const client = entry.client;
+ if (!client || entry.state !== 'connected') {
+ throw new Error(`server ${entry.id} is ${entry.state}`);
+ }
+ const generation = entry.generation;
+ try {
+ return await client.callTool(
+ { name: toolName, arguments: args },
+ { signal, timeout: entry.config.timeoutMs ?? DEFAULT_CALL_TIMEOUT_MS },
+ );
+ } catch (err) {
+ if (isConnectionError(err)) this.scheduleReconnect(entry, errorMessage(err), generation);
+ throw err;
+ }
+ }
+}
diff --git a/src/capabilities/mcp/naming.test.ts b/src/capabilities/mcp/naming.test.ts
new file mode 100644
index 00000000..89288475
--- /dev/null
+++ b/src/capabilities/mcp/naming.test.ts
@@ -0,0 +1,41 @@
+import { describe, expect, it } from 'vitest';
+import { exposedToolName, isMcpToolName, MAX_TOOL_NAME_LENGTH, sanitizeToolPart } from './naming.js';
+
+describe('MCP tool naming', () => {
+ it('prefixes tools with the server id', () => {
+ expect(exposedToolName('github', 'search_issues', new Set())).toBe('mcp__github__search_issues');
+ expect(isMcpToolName('mcp__github__search_issues')).toBe(true);
+ expect(isMcpToolName('read_file')).toBe(false);
+ });
+
+ it('replaces characters providers reject', () => {
+ expect(sanitizeToolPart('files.read/v2 beta')).toBe('files_read_v2_beta');
+ expect(sanitizeToolPart('')).toBe('_');
+ expect(exposedToolName('docs', 'get.page', new Set())).toBe('mcp__docs__get_page');
+ });
+
+ it('caps long names at 64 characters with a stable hash suffix', () => {
+ const long = 'a'.repeat(80);
+ const name = exposedToolName('server-with-long-id', long, new Set());
+ expect(name.length).toBe(MAX_TOOL_NAME_LENGTH);
+ expect(name).toMatch(/^mcp__server-with-long-id__a+_[0-9a-f]{6}$/);
+ expect(exposedToolName('server-with-long-id', long, new Set())).toBe(name);
+ });
+
+ it('adds a hash when two tools sanitize to the same name', () => {
+ const first = exposedToolName('docs', 'get.page', new Set());
+ const second = exposedToolName('docs', 'get page', new Set([first]));
+ expect(second).not.toBe(first);
+ expect(second).toMatch(/^mcp__docs__get_page_[0-9a-f]{6}$/);
+ });
+
+ it('is never mistaken for a plugin tool, and no plugin can take the id "mcp"', async () => {
+ const { isPluginToolName, pluginToolAllowed } = await import('../../plugins/tool-bridge.js');
+ const { RESERVED_PLUGIN_IDS, RESERVED_COMMANDS } = await import('../../plugins/types.js');
+ expect(isPluginToolName('mcp__github__search_issues')).toBe(false);
+ expect(pluginToolAllowed('mcp__github__search_issues', ['mcp__*', 'mcp__github__search_issues'])).toBe(false);
+ expect(isPluginToolName('whatsapp__send_message')).toBe(true);
+ expect(RESERVED_PLUGIN_IDS.has('mcp')).toBe(true);
+ expect(RESERVED_COMMANDS.has('mcp')).toBe(true);
+ });
+});
diff --git a/src/capabilities/mcp/naming.ts b/src/capabilities/mcp/naming.ts
new file mode 100644
index 00000000..bc7febf0
--- /dev/null
+++ b/src/capabilities/mcp/naming.ts
@@ -0,0 +1,24 @@
+import { createHash } from 'node:crypto';
+
+export const MCP_TOOL_PREFIX = 'mcp__';
+export const MAX_TOOL_NAME_LENGTH = 64;
+
+export function isMcpToolName(name: string): boolean {
+ return name.startsWith(MCP_TOOL_PREFIX);
+}
+
+export function sanitizeToolPart(name: string): string {
+ const cleaned = name.replace(/[^A-Za-z0-9_-]/g, '_');
+ return cleaned || '_';
+}
+
+function shortHash(serverId: string, toolName: string): string {
+ return createHash('sha256').update(`${serverId}/${toolName}`).digest('hex').slice(0, 6);
+}
+
+export function exposedToolName(serverId: string, toolName: string, taken: ReadonlySet<string>): string {
+ const base = `${MCP_TOOL_PREFIX}${serverId}__${sanitizeToolPart(toolName)}`;
+ if (base.length <= MAX_TOOL_NAME_LENGTH && !taken.has(base)) return base;
+ const suffix = `_${shortHash(serverId, toolName)}`;
+ return `${base.slice(0, MAX_TOOL_NAME_LENGTH - suffix.length)}${suffix}`;
+}
diff --git a/src/capabilities/mcp/result.test.ts b/src/capabilities/mcp/result.test.ts
new file mode 100644
index 00000000..2dcc2086
--- /dev/null
+++ b/src/capabilities/mcp/result.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+import { registerSecretValue } from '../../utils/redact.js';
+import { callResultToText, MAX_RESULT_CHARS } from './result.js';
+
+describe('callResultToText', () => {
+ it('joins text blocks', () => {
+ const text = callResultToText({
+ content: [
+ { type: 'text', text: 'one' },
+ { type: 'text', text: 'two' },
+ ],
+ });
+ expect(text).toBe('one\ntwo');
+ });
+
+ it('replaces media with a placeholder', () => {
+ const text = callResultToText({
+ content: [
+ { type: 'text', text: 'a pixel' },
+ { type: 'image', data: 'AAAA', mimeType: 'image/png' },
+ { type: 'audio', data: 'AAAAAAAA', mimeType: 'audio/wav' },
+ ],
+ });
+ expect(text).toBe('a pixel\n[image/png, 3 B — not shown]\n[audio/wav, 6 B — not shown]');
+ });
+
+ it('renders resources and links', () => {
+ const text = callResultToText({
+ content: [
+ { type: 'resource', resource: { uri: 'file:///a.txt', text: 'inline body' } },
+ { type: 'resource', resource: { uri: 'file:///b.bin', blob: 'AAAA', mimeType: 'application/octet-stream' } },
+ { type: 'resource_link', uri: 'file:///c.txt', name: 'c' },
+ ],
+ });
+ expect(text).toBe(
+ 'inline body\n[resource file:///b.bin (application/octet-stream) — not shown]\n[resource link: file:///c.txt]',
+ );
+ });
+
+ it('falls back to structured content, then to a placeholder', () => {
+ expect(callResultToText({ content: [], structuredContent: { ok: true } })).toBe('{\n "ok": true\n}');
+ expect(callResultToText({ content: [] })).toBe('(no content)');
+ });
+
+ it('prefixes errors so the agent treats them as failures', () => {
+ expect(callResultToText({ content: [{ type: 'text', text: 'boom' }], isError: true })).toBe('Error: boom');
+ expect(callResultToText({ isError: true })).toBe('Error: the server reported an error without details');
+ });
+
+ it('truncates long results', () => {
+ const text = callResultToText({ content: [{ type: 'text', text: 'x'.repeat(MAX_RESULT_CHARS + 10) }] });
+ expect(text.startsWith('x'.repeat(MAX_RESULT_CHARS))).toBe(true);
+ expect(text.endsWith('… (truncated, 10 chars omitted)')).toBe(true);
+ });
+
+ it('redacts registered secrets', () => {
+ const secret = ['result-secret-', 'value-77'].join('');
+ registerSecretValue(secret);
+ expect(callResultToText({ content: [{ type: 'text', text: `value=${secret}` }] })).toBe('value=****');
+ });
+});
diff --git a/src/capabilities/mcp/result.ts b/src/capabilities/mcp/result.ts
new file mode 100644
index 00000000..5a022a80
--- /dev/null
+++ b/src/capabilities/mcp/result.ts
@@ -0,0 +1,69 @@
+import { redactSecrets } from '../../utils/redact.js';
+
+export const MAX_RESULT_CHARS = 32 * 1024;
+
+interface ContentBlock {
+ type?: string;
+ text?: string;
+ data?: string;
+ mimeType?: string;
+ uri?: string;
+ name?: string;
+ resource?: { uri?: string; text?: string; blob?: string; mimeType?: string };
+}
+
+export interface McpCallResultLike {
+ content?: unknown;
+ structuredContent?: unknown;
+ isError?: boolean;
+}
+
+function base64Bytes(data: string | undefined): number {
+ if (!data) return 0;
+ const padding = data.endsWith('==') ? 2 : data.endsWith('=') ? 1 : 0;
+ return Math.max(0, Math.floor((data.length * 3) / 4) - padding);
+}
+
+function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+function blockToText(block: ContentBlock): string {
+ switch (block.type) {
+ case 'text':
+ return block.text ?? '';
+ case 'image':
+ case 'audio':
+ return `[${block.mimeType ?? block.type}, ${formatBytes(base64Bytes(block.data))} — not shown]`;
+ case 'resource': {
+ const resource = block.resource ?? {};
+ if (typeof resource.text === 'string') return resource.text;
+ return `[resource ${resource.uri ?? ''} (${resource.mimeType ?? 'binary'}) — not shown]`;
+ }
+ case 'resource_link':
+ return `[resource link: ${block.uri ?? block.name ?? ''}]`;
+ default:
+ return `[${block.type ?? 'unknown'} content — not shown]`;
+ }
+}
+
+function truncate(text: string): string {
+ if (text.length <= MAX_RESULT_CHARS) return text;
+ const omitted = text.length - MAX_RESULT_CHARS;
+ return `${text.slice(0, MAX_RESULT_CHARS)}\n… (truncated, ${omitted} chars omitted)`;
+}
+
+export function callResultToText(result: McpCallResultLike): string {
+ const blocks = Array.isArray(result.content) ? (result.content as ContentBlock[]) : [];
+ let text = blocks.map(blockToText).filter((part) => part.length > 0).join('\n');
+ if (!text && result.structuredContent !== undefined) {
+ text = JSON.stringify(result.structuredContent, null, 2) ?? '';
+ }
+ if (!text) {
+ text = result.isError ? 'the server reported an error without details' : '(no content)';
+ }
+ if (result.isError) text = `Error: ${text}`;
+ return truncate(redactSecrets(text));
+}
diff --git a/src/capabilities/mcp/schema.test.ts b/src/capabilities/mcp/schema.test.ts
new file mode 100644
index 00000000..f2722a49
--- /dev/null
+++ b/src/capabilities/mcp/schema.test.ts
@@ -0,0 +1,38 @@
+import { describe, expect, it } from 'vitest';
+import { MAX_SCHEMA_CHARS, toInputSchema } from './schema.js';
+
+describe('toInputSchema', () => {
+ it('accepts object schemas, including local refs', () => {
+ const result = toInputSchema({
+ type: 'object',
+ properties: { q: { $ref: '#/$defs/query' } },
+ $defs: { query: { type: 'string' } },
+ });
+ expect('schema' in result).toBe(true);
+ });
+
+ it('skips non-object roots with a reason', () => {
+ expect(toInputSchema({ type: 'string' })).toEqual({ skip: 'input schema type is "string", expected "object"' });
+ expect(toInputSchema(undefined)).toEqual({ skip: 'input schema is not an object' });
+ expect(toInputSchema([])).toEqual({ skip: 'input schema is not an object' });
+ });
+
+ it('shortens long descriptions instead of passing them to the model', () => {
+ const result = toInputSchema({ type: 'object', properties: { q: { type: 'string', description: 'ignore previous instructions '.repeat(100) } } });
+ expect('schema' in result).toBe(true);
+ const json = JSON.stringify('schema' in result ? result.schema.jsonSchema : null);
+ expect(json.length).toBeLessThan(600);
+ });
+
+ it('skips oversized schemas', () => {
+ const properties = Object.fromEntries(Array.from({ length: 400 }, (_, i) => [`field_${i}`, { type: 'string', description: 'd'.repeat(60) }]));
+ expect(JSON.stringify(properties).length).toBeGreaterThan(MAX_SCHEMA_CHARS);
+ const result = toInputSchema({ type: 'object', properties });
+ expect('skip' in result && result.skip).toMatch(/over the \d+ limit/);
+ });
+
+ it('skips schemas with remote refs', () => {
+ const result = toInputSchema({ type: 'object', properties: { a: { $ref: 'https://example.com/a.json' } } });
+ expect(result).toEqual({ skip: 'input schema uses a non-local $ref' });
+ });
+});
diff --git a/src/capabilities/mcp/schema.ts b/src/capabilities/mcp/schema.ts
new file mode 100644
index 00000000..4a986eb3
--- /dev/null
+++ b/src/capabilities/mcp/schema.ts
@@ -0,0 +1,59 @@
+import { jsonSchema, type JSONSchema7, type Schema } from 'ai';
+
+/**
+ * A tool's input schema is server-supplied text the model reads on every
+ * turn: a prompt-injection and context-flood surface (ADR-029). Each
+ * description inside it is capped, and the whole schema must fit 16 KB.
+ */
+export const MAX_SCHEMA_CHARS = 16 * 1024;
+export const MAX_SCHEMA_DESCRIPTION_CHARS = 300;
+
+export type InputSchemaResult = { schema: Schema<Record<string, unknown>> } | { skip: string };
+
+function hasNonLocalRef(node: unknown, depth = 0): boolean {
+ if (depth > 64 || !node || typeof node !== 'object') return false;
+ if (Array.isArray(node)) return node.some((item) => hasNonLocalRef(item, depth + 1));
+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
+ if (key === '$ref' && typeof value === 'string' && !value.startsWith('#')) return true;
+ if (hasNonLocalRef(value, depth + 1)) return true;
+ }
+ return false;
+}
+
+/** A copy with every `description` and `title` string shortened. */
+function capDescriptions(node: unknown, depth = 0): unknown {
+ if (depth > 64 || !node || typeof node !== 'object') return node;
+ if (Array.isArray(node)) return node.map((item) => capDescriptions(item, depth + 1));
+ const out: Record<string, unknown> = {};
+ for (const [key, value] of Object.entries(node as Record<string, unknown>)) {
+ if ((key === 'description' || key === 'title') && typeof value === 'string' && value.length > MAX_SCHEMA_DESCRIPTION_CHARS) {
+ out[key] = `${value.slice(0, MAX_SCHEMA_DESCRIPTION_CHARS)}…`;
+ } else {
+ out[key] = capDescriptions(value, depth + 1);
+ }
+ }
+ return out;
+}
+
+export function toInputSchema(inputSchema: unknown): InputSchemaResult {
+ if (!inputSchema || typeof inputSchema !== 'object' || Array.isArray(inputSchema)) {
+ return { skip: 'input schema is not an object' };
+ }
+ const schema = capDescriptions(inputSchema) as Record<string, unknown>;
+ if (schema.type !== 'object') {
+ return { skip: `input schema type is ${JSON.stringify(schema.type ?? null)}, expected "object"` };
+ }
+ let serialized: string;
+ try {
+ serialized = JSON.stringify(schema);
+ } catch {
+ return { skip: 'input schema cannot be serialized' };
+ }
+ if (serialized.length > MAX_SCHEMA_CHARS) {
+ return { skip: `input schema is ${serialized.length} characters, over the ${MAX_SCHEMA_CHARS} limit` };
+ }
+ if (hasNonLocalRef(schema)) {
+ return { skip: 'input schema uses a non-local $ref' };
+ }
+ return { schema: jsonSchema<Record<string, unknown>>(schema as JSONSchema7) };
+}
diff --git a/src/capabilities/mcp/sdk-smoke.test.ts b/src/capabilities/mcp/sdk-smoke.test.ts
new file mode 100644
index 00000000..86fee193
--- /dev/null
+++ b/src/capabilities/mcp/sdk-smoke.test.ts
@@ -0,0 +1,140 @@
+import { afterAll, afterEach, beforeAll, describe, expect, it } from 'vitest';
+import { spawn, type ChildProcess } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+import { Client, StreamableHTTPClientTransport, type Tool } from '@modelcontextprotocol/client';
+import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/client/stdio';
+
+const FIXTURE = fileURLToPath(new URL('./fixtures/mcp-fixture-server.mjs', import.meta.url));
+const TOKEN = 'fixture-token-0123456789';
+
+type Content = { type: string; text?: string; mimeType?: string };
+
+const clients: Client[] = [];
+
+function newClient(options?: ConstructorParameters<typeof Client>[1]): Client {
+ const client = new Client({ name: 'mercury-test', version: '0.0.0' }, options);
+ clients.push(client);
+ return client;
+}
+
+function stdioTransport(env: Record<string, string> = {}): StdioClientTransport {
+ return new StdioClientTransport({
+ command: process.execPath,
+ args: [FIXTURE],
+ env: { ...getDefaultEnvironment(), ...env },
+ stderr: 'pipe',
+ });
+}
+
+function firstText(result: { content?: unknown }): string {
+ const content = (result.content ?? []) as Content[];
+ return content.find((c) => c.type === 'text')?.text ?? '';
+}
+
+afterEach(async () => {
+ await Promise.allSettled(clients.splice(0).map((c) => c.close()));
+});
+
+describe('MCP v2 client over stdio', () => {
+ it('lists and calls tools', async () => {
+ const client = newClient();
+ await client.connect(stdioTransport());
+
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name)).toEqual(expect.arrayContaining(['echo', 'add', 'image', 'fail']));
+
+ expect(firstText(await client.callTool({ name: 'echo', arguments: { text: 'hi' } }))).toBe('hi');
+
+ const image = await client.callTool({ name: 'image', arguments: {} });
+ const parts = image.content as Content[];
+ expect(parts.map((p) => p.type)).toEqual(['text', 'image']);
+ expect(parts[1]?.mimeType).toBe('image/png');
+
+ const failed = await client.callTool({ name: 'fail', arguments: {} });
+ expect(failed.isError).toBe(true);
+ }, 20_000);
+
+ it('only passes the environment it is given', async () => {
+ process.env.MCP_FIXTURE_HIDDEN = 'parent-only-value';
+ try {
+ const client = newClient();
+ await client.connect(stdioTransport({ MCP_FIXTURE_VISIBLE: 'given' }));
+ expect(firstText(await client.callTool({ name: 'read_env', arguments: { name: 'MCP_FIXTURE_VISIBLE' } }))).toBe('given');
+ expect(firstText(await client.callTool({ name: 'read_env', arguments: { name: 'MCP_FIXTURE_HIDDEN' } }))).toBe('(unset)');
+ } finally {
+ delete process.env.MCP_FIXTURE_HIDDEN;
+ }
+ }, 20_000);
+
+ it('refreshes tools on tools/list_changed', async () => {
+ let resolveChanged!: (tools: Tool[]) => void;
+ const changed = new Promise<Tool[]>((resolve) => {
+ resolveChanged = resolve;
+ });
+ const client = newClient({
+ listChanged: {
+ tools: {
+ debounceMs: 0,
+ onChanged: (error, tools) => {
+ if (!error && tools) resolveChanged(tools);
+ },
+ },
+ },
+ });
+ await client.connect(stdioTransport());
+ await client.callTool({ name: 'add_tool', arguments: { name: 'late_tool' } });
+ const tools = await changed;
+ expect(tools.map((t) => t.name)).toContain('late_tool');
+ }, 20_000);
+});
+
+describe('MCP v2 client over Streamable HTTP', () => {
+ let server: ChildProcess;
+ let url: URL;
+
+ beforeAll(async () => {
+ server = spawn(process.execPath, [FIXTURE, '--http', '0'], {
+ env: { ...process.env, FIXTURE_REQUIRE_TOKEN: TOKEN },
+ stdio: ['ignore', 'pipe', 'inherit'],
+ });
+ const port = await new Promise<number>((resolve, reject) => {
+ let buffered = '';
+ server.stdout!.on('data', (chunk: Buffer) => {
+ buffered += chunk.toString();
+ const match = /LISTENING (\d+)/.exec(buffered);
+ if (match) resolve(Number(match[1]));
+ });
+ server.once('exit', (code) => reject(new Error(`fixture exited with ${code}`)));
+ });
+ url = new URL(`http://127.0.0.1:${port}/mcp`);
+ }, 20_000);
+
+ afterAll(() => {
+ server?.kill();
+ });
+
+ it('connects through a custom fetch with static headers', async () => {
+ let calls = 0;
+ const countingFetch: typeof fetch = (input, init) => {
+ calls += 1;
+ return fetch(input, init);
+ };
+ const client = newClient();
+ await client.connect(
+ new StreamableHTTPClientTransport(url, {
+ fetch: countingFetch,
+ requestInit: { headers: { Authorization: `Bearer ${TOKEN}` } },
+ }),
+ );
+
+ const { tools } = await client.listTools();
+ expect(tools.map((t) => t.name)).toContain('add');
+ expect(firstText(await client.callTool({ name: 'add', arguments: { a: 2, b: 3 } }))).toBe('5');
+ expect(calls).toBeGreaterThan(0);
+ }, 20_000);
+
+ it('fails to connect without the token', async () => {
+ const client = newClient();
+ await expect(client.connect(new StreamableHTTPClientTransport(url))).rejects.toThrow();
+ }, 20_000);
+});
diff --git a/src/capabilities/mcp/tool.ts b/src/capabilities/mcp/tool.ts
new file mode 100644
index 00000000..f0222537
--- /dev/null
+++ b/src/capabilities/mcp/tool.ts
@@ -0,0 +1,56 @@
+import { tool, type Schema, type Tool } from 'ai';
+import { redactSecrets } from '../../utils/redact.js';
+import { callResultToText, type McpCallResultLike } from './result.js';
+import type { McpGate } from './types.js';
+
+export const MAX_DESCRIPTION_CHARS = 1024;
+
+export type McpToolCaller = (
+ toolName: string,
+ args: Record<string, unknown>,
+ signal: AbortSignal | undefined,
+) => Promise<McpCallResultLike>;
+
+export interface BuildMcpToolOptions {
+ serverId: string;
+ toolName: string;
+ exposedName: string;
+ description: string | undefined;
+ inputSchema: Schema<Record<string, unknown>>;
+ autoApprove: boolean;
+ gate: McpGate;
+ call: McpToolCaller;
+}
+
+export function describeMcpTool(serverId: string, description: string | undefined): string {
+ const text = `[MCP: ${serverId}] ${(description ?? '').trim()}`.trim();
+ return text.length > MAX_DESCRIPTION_CHARS ? `${text.slice(0, MAX_DESCRIPTION_CHARS - 1)}…` : text;
+}
+
+function errorMessage(err: unknown): string {
+ return err instanceof Error ? err.message : String(err);
+}
+
+export function buildMcpTool(options: BuildMcpToolOptions): Tool {
+ const { serverId, toolName, exposedName, autoApprove, gate, call } = options;
+ return tool({
+ description: describeMcpTool(serverId, options.description),
+ inputSchema: options.inputSchema,
+ execute: async (args: Record<string, unknown>, { abortSignal }): Promise<string> => {
+ let verdict;
+ try {
+ verdict = await gate({ serverId, toolName, exposedName, args, autoApprove });
+ } catch (err) {
+ return `Error: permission check for MCP ${serverId}/${toolName} failed: ${redactSecrets(errorMessage(err))}`;
+ }
+ if (!verdict.allowed) {
+ return `Error: ${verdict.reason ?? `MCP ${serverId}/${toolName} is not permitted`}`;
+ }
+ try {
+ return callResultToText(await call(toolName, args ?? {}, abortSignal));
+ } catch (err) {
+ return `Error: MCP ${serverId}/${toolName} failed: ${redactSecrets(errorMessage(err))}`;
+ }
+ },
+ });
+}
diff --git a/src/capabilities/mcp/transport.test.ts b/src/capabilities/mcp/transport.test.ts
new file mode 100644
index 00000000..27cad4f3
--- /dev/null
+++ b/src/capabilities/mcp/transport.test.ts
@@ -0,0 +1,30 @@
+import { describe, expect, it } from 'vitest';
+import { registerSecretValue } from '../../utils/redact.js';
+import { appendStderr, renderStderrTail, STDERR_TAIL_CHARS } from './transport.js';
+
+const secret = ['stderr-secret-', 'value-ABCDEFGHIJ'].join('');
+registerSecretValue(secret);
+
+describe('stderr tail', () => {
+ it('masks a secret in a short tail', () => {
+ expect(renderStderrTail(appendStderr('', `token ${secret}\n`))).toBe('token ****\n');
+ });
+
+ it('never shows part of a secret when the window cuts through it', () => {
+ let raw = appendStderr('', `token ${secret}\n`);
+ raw = appendStderr(raw, 'x'.repeat(STDERR_TAIL_CHARS - 15));
+ const tail = renderStderrTail(raw);
+ expect(tail.length).toBeLessThanOrEqual(STDERR_TAIL_CHARS);
+ expect(tail).not.toContain(secret);
+ expect(tail).not.toContain(secret.slice(-10));
+ });
+
+ it('drops a cut-off first line once the raw buffer is full', () => {
+ let raw = appendStderr('', `aaaaa${secret}\nsecond line\n`);
+ raw = appendStderr(raw, 'y'.repeat(2 * STDERR_TAIL_CHARS - 20));
+ expect(raw.length).toBe(2 * STDERR_TAIL_CHARS);
+ const tail = renderStderrTail(raw);
+ expect(tail.length).toBeLessThanOrEqual(STDERR_TAIL_CHARS);
+ expect(tail).not.toContain(secret.slice(-10));
+ });
+});
diff --git a/src/capabilities/mcp/transport.ts b/src/capabilities/mcp/transport.ts
new file mode 100644
index 00000000..cdb2fccd
--- /dev/null
+++ b/src/capabilities/mcp/transport.ts
@@ -0,0 +1,68 @@
+import { basename } from 'node:path';
+import { StreamableHTTPClientTransport, type Transport } from '@modelcontextprotocol/client';
+import { StdioClientTransport, getDefaultEnvironment } from '@modelcontextprotocol/client/stdio';
+import { createGuardedFetch } from '../../utils/ssrf.js';
+import { redactSecrets } from '../../utils/redact.js';
+import type { ResolvedSecrets } from './config.js';
+import type { McpServerConfig } from './types.js';
+
+export const STDERR_TAIL_CHARS = 8 * 1024;
+const STDERR_RAW_CHARS = 2 * STDERR_TAIL_CHARS;
+
+export function appendStderr(raw: string, chunk: string): string {
+ return (raw + chunk).slice(-STDERR_RAW_CHARS);
+}
+
+export function renderStderrTail(raw: string): string {
+ let text = raw;
+ if (raw.length >= STDERR_RAW_CHARS) {
+ const newline = text.indexOf('\n');
+ if (newline !== -1) text = text.slice(newline + 1);
+ }
+ return redactSecrets(text).slice(-STDERR_TAIL_CHARS);
+}
+
+export interface CreatedTransport {
+ transport: Transport;
+ stderrTail: () => string;
+}
+
+export function describeTarget(server: McpServerConfig): string {
+ if (server.transport === 'stdio') return basename(server.command ?? '');
+ try {
+ return new URL(server.url ?? '').origin;
+ } catch {
+ return '';
+ }
+}
+
+function createStdioTransport(server: McpServerConfig, resolved: ResolvedSecrets): CreatedTransport {
+ const transport = new StdioClientTransport({
+ command: server.command ?? '',
+ args: resolved.args,
+ cwd: server.cwd,
+ env: { ...getDefaultEnvironment(), ...resolved.env },
+ stderr: 'pipe',
+ });
+ let raw = '';
+ transport.stderr?.on('data', (chunk: Buffer | string) => {
+ raw = appendStderr(raw, chunk.toString());
+ });
+ return { transport, stderrTail: () => renderStderrTail(raw) };
+}
+
+function createHttpTransport(server: McpServerConfig, resolved: ResolvedSecrets): CreatedTransport {
+ const transport = new StreamableHTTPClientTransport(new URL(server.url ?? ''), {
+ fetch: createGuardedFetch({
+ allowPrivate: server.allowPrivate === true,
+ privateHint: 'Set allowPrivate: true for this MCP server (or add it with --allow-private) if you trust it.',
+ }),
+ requestInit: { headers: resolved.headers },
+ redirectPolicy: 'same-origin',
+ });
+ return { transport, stderrTail: () => '' };
+}
+
+export function createTransport(server: McpServerConfig, resolved: ResolvedSecrets): CreatedTransport {
+ return server.transport === 'stdio' ? createStdioTransport(server, resolved) : createHttpTransport(server, resolved);
+}
diff --git a/src/capabilities/mcp/types.ts b/src/capabilities/mcp/types.ts
new file mode 100644
index 00000000..95730ae1
--- /dev/null
+++ b/src/capabilities/mcp/types.ts
@@ -0,0 +1,62 @@
+export type McpTransportKind = 'stdio' | 'http';
+
+export interface McpToolFilter {
+ allow?: string[];
+ deny?: string[];
+ autoApprove?: string[];
+}
+
+export interface McpServerConfig {
+ transport: McpTransportKind;
+ command?: string;
+ args?: string[];
+ env?: Record<string, string>;
+ cwd?: string;
+ url?: string;
+ headers?: Record<string, string>;
+ allowPrivate?: boolean;
+ enabled?: boolean;
+ timeoutMs?: number;
+ tools?: McpToolFilter;
+}
+
+export interface McpConfig {
+ servers?: Record<string, McpServerConfig>;
+}
+
+export type McpServerState = 'disabled' | 'connecting' | 'connected' | 'reconnecting' | 'failed';
+
+export interface McpToolStatus {
+ name: string;
+ exposedName: string;
+ allowed: boolean;
+ autoApprove: boolean;
+ skipped?: string;
+}
+
+export interface McpServerStatus {
+ id: string;
+ transport: McpTransportKind;
+ enabled: boolean;
+ state: McpServerState;
+ target: string;
+ error?: string;
+ toolCount: number;
+ tools: McpToolStatus[];
+ stderrTail?: string;
+}
+
+export interface McpGateRequest {
+ serverId: string;
+ toolName: string;
+ exposedName: string;
+ args: unknown;
+ autoApprove: boolean;
+}
+
+export interface McpGateResult {
+ allowed: boolean;
+ reason?: string;
+}
+
+export type McpGate = (request: McpGateRequest) => Promise<McpGateResult>;
diff --git a/src/capabilities/permissions.ts b/src/capabilities/permissions.ts
index 41d58bf2..882479da 100644
--- a/src/capabilities/permissions.ts
+++ b/src/capabilities/permissions.ts
@@ -4,6 +4,7 @@ import { homedir } from 'node:os';
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { getMercuryHome } from '../utils/config.js';
import { logger } from '../utils/logger.js';
+import { redactSecrets } from '../utils/redact.js';
import { BLOCKED_COMMANDS } from './shell/blocklist.js';
import {
evaluateArgvPolicy,
@@ -19,8 +20,52 @@ import {
type ContextScope,
} from './permission-context.js';
+import type { McpGateRequest, McpGateResult } from './mcp/types.js';
+
export type { PermissionContext } from './permission-context.js';
+/**
+ * Arguments as the owner sees them in an approval prompt. Up to 4,000
+ * characters are shown whole. Longer ones keep the start AND the end, with
+ * the size of the hidden middle, so a payload can't hide after a cut.
+ */
+const MCP_ARGS_SHOW_ALL = 4000;
+const MCP_ARGS_HEAD = 2400;
+const MCP_ARGS_TAIL = 1200;
+
+export function formatMcpArgs(args: unknown): string {
+ let text: string;
+ try {
+ text = JSON.stringify(args ?? {}, null, 2) ?? '{}';
+ } catch {
+ text = String(args);
+ }
+ text = redactSecrets(text);
+ if (text.length <= MCP_ARGS_SHOW_ALL) return text;
+ const hidden = text.length - MCP_ARGS_HEAD - MCP_ARGS_TAIL;
+ return `${text.slice(0, MCP_ARGS_HEAD)}\n… [${hidden.toLocaleString('en-US')} characters not shown; the start and end are] …\n${text.slice(-MCP_ARGS_TAIL)}`;
+}
+
+/**
+ * A shell segment that changes MCP setup: `mercury mcp add|remove|enable|
+ * disable|allow|disallow`, or anything that names mercury.yaml (sed -i,
+ * tee, cp, mv, echo >>). Reading it is caught too; that only costs a prompt.
+ */
+export function changesMcpSetup(segment: string): boolean {
+ return /\bmcp\s+(add|remove|rm|enable|disable|allow|disallow)\b/.test(segment)
+ || /mercury\.ya?ml/i.test(segment);
+}
+
+function protectedConfigPaths(): string[] {
+ const home = getMercuryHome();
+ return [
+ join(home, 'mercury.yaml'),
+ join(home, 'permissions.yaml'),
+ join(home, '.env'),
+ join(homedir(), '.mercury', '.env'),
+ ];
+}
+
/** Result of a shell permission check. */
export interface ShellCheckResult {
allowed: boolean;
@@ -368,6 +413,7 @@ export class PermissionManager {
/** "Always allow" choices for plugin tools, per channel (see approvePluginTool). */
private approvedPluginToolsByContext = new Map<string, Set<string>>();
private approvedWritesByContext = new Map<string, Set<string>>();
+ private approvedMcpByContext = new Map<string, Set<string>>();
/** Hard-linked files the user answered "always" for, per interaction context. */
private approvedHardlinkReadsByContext = new Map<string, Set<string>>();
/**
@@ -787,6 +833,9 @@ export class PermissionManager {
}
private async checkScopedAccess(path: string, mode: 'read' | 'write'): Promise<FsAccessResult> {
+ if (mode === 'write' && this.isProtectedConfigPath(path)) {
+ return this.confirmConfigWrite(path);
+ }
if (mode === 'read' && this.isElevated('fs_read')) {
return { allowed: true };
}
@@ -910,6 +959,21 @@ export class PermissionManager {
}
}
+ // Adding or changing an MCP server is an owner action (ADR-029): a shell
+ // command that does it asks every time, Allow All and earlier "always"
+ // answers included, and never runs unattended. Otherwise an injected
+ // prompt could add a server whose autoApprove tools then run in
+ // scheduled turns.
+ if (segments.some(changesMcpSetup)) {
+ if (!this.askHandler || ctx.channelType === 'internal' || this.failClosed) {
+ return { allowed: false, reason: 'Changing MCP servers or mercury.yaml from a shell command needs the owner; run it yourself in a terminal', needsApproval: false };
+ }
+ const answer = await this.askHandler(`Run command (changes Mercury's MCP servers or config, so it always asks): ${trimmed}`);
+ return answer === 'yes' || answer === 'always'
+ ? { allowed: true, needsApproval: false, lane: 'shell' }
+ : { allowed: false, reason: `User denied: ${trimmed}`, needsApproval: false };
+ }
+
if (this.isGlobalAutoApproveActive()) {
logger.info({ cmd: trimmed }, 'Shell command auto-approved (Local allow-all mode)');
return { allowed: true, needsApproval: false, lane: 'shell' };
@@ -1024,6 +1088,59 @@ export class PermissionManager {
return { allowed: false, reason: 'Command not in auto-approve list — requires approval', needsApproval: true };
}
+ async checkMcpTool(request: McpGateRequest): Promise<McpGateResult> {
+ const { serverId, toolName } = request;
+ const label = `${serverId}/${toolName}`;
+ if (request.autoApprove) return { allowed: true };
+ if (this.failClosed) {
+ return { allowed: false, reason: `Fail-closed: MCP tool ${label} is not in tools.autoApprove` };
+ }
+ const ctx = this.ctx();
+ if (this.approvedMcpByContext.get(ctx.channelId)?.has(label)) return { allowed: true };
+ if (!this.askHandler || ctx.channelType === 'internal') {
+ return {
+ allowed: false,
+ reason: `MCP tool ${label} needs approval; add "${toolName}" to tools.autoApprove for server "${serverId}" to run it unattended`,
+ };
+ }
+ const answer = await this.askHandler(
+ `MCP tool call\nServer: ${serverId}\nTool: ${toolName}\nArguments:\n${formatMcpArgs(request.args)}`,
+ );
+ if (answer === 'yes') return { allowed: true };
+ if (answer === 'always') {
+ const approved = this.approvedMcpByContext.get(ctx.channelId) ?? new Set<string>();
+ approved.add(label);
+ this.approvedMcpByContext.set(ctx.channelId, approved);
+ return { allowed: true };
+ }
+ return { allowed: false, reason: `User denied MCP tool ${label}` };
+ }
+
+ private isProtectedConfigPath(path: string): boolean {
+ const caseInsensitive = process.platform === 'win32' || process.platform === 'darwin';
+ const normalize = (p: string) => (caseInsensitive ? p.toLowerCase() : p);
+ const protectedPaths = new Set(
+ protectedConfigPaths().flatMap((p) => [resolve(p), this.canonicalizePath(resolve(p))]).map(normalize),
+ );
+ const resolved = resolve(path);
+ return [resolved, this.canonicalizePath(resolved)].some((candidate) => protectedPaths.has(normalize(candidate)));
+ }
+
+ private async confirmConfigWrite(path: string): Promise<FsAccessResult> {
+ const resolved = resolve(path);
+ if (this.failClosed || !this.askHandler || this.ctx().channelType === 'internal') {
+ return {
+ allowed: false,
+ reason: `Permission denied: ${resolved} is a Mercury config file and can only be changed with the owner's confirmation`,
+ };
+ }
+ const answer = await this.askHandler(
+ `Write to Mercury config file: ${resolved}\n(it controls MCP servers, permissions and secrets)`,
+ );
+ if (answer === 'yes' || answer === 'always') return { allowed: true };
+ return { allowed: false, reason: `User denied write to ${path}` };
+ }
+
/**
* Argv-lane classification: policy (tokenizer, allowlist, flag policy),
* binary availability in the pinned PATH, and a path gate over the
diff --git a/src/capabilities/registry.ts b/src/capabilities/registry.ts
index 2ba69814..58f3c161 100644
--- a/src/capabilities/registry.ts
+++ b/src/capabilities/registry.ts
@@ -70,6 +70,8 @@ import { getPluginTools } from '../plugins/tool-bridge.js';
import { createDispatchBotTool } from '../bots/tools/dispatch-bot.js';
import type { UserMemoryStore } from '../memory/user-memory.js';
import { logger } from '../utils/logger.js';
+import type { McpManager } from './mcp/manager.js';
+import type { McpServerStatus } from './mcp/types.js';
export interface ChatCommandContext {
toolNames: () => string[];
@@ -85,6 +87,7 @@ export interface ChatCommandContext {
memoryGetSubconscious: (limit?: number) => import('../memory/user-memory.js').UserMemoryRecord[];
memoryIsShareLearning: () => boolean;
memorySetShareLearning: (enabled: boolean) => void;
+ mcpStatus?: () => McpServerStatus[];
}
export class CapabilityRegistry {
@@ -101,6 +104,7 @@ export class CapabilityRegistry {
private chatCommandContext?: ChatCommandContext;
private currentCwd = process.cwd();
private researchModeGetter: (() => boolean) | null = null;
+ private mcp?: McpManager;
/**
* Mercury Bots dispatch handler — set once the BotManager exists
@@ -309,6 +313,18 @@ export class CapabilityRegistry {
logger.info('Interaction tools registered');
}
+ attachMcp(manager: McpManager): void {
+ this.mcp = manager;
+ }
+
+ getMcpManager(): McpManager | undefined {
+ return this.mcp;
+ }
+
+ private allTools(): Record<string, Tool> {
+ return this.mcp ? { ...this.tools, ...this.mcp.getTools() } : this.tools;
+ }
+
getTools(): Record<string, Tool> {
if (this.toolsDisabled) return {};
// Scheduled calls (when a calling channel plugin is running): owner only.
@@ -322,7 +338,7 @@ export class CapabilityRegistry {
// Members on a channel that distinguishes roles (e.g. Telegram) must not be
// able to install skills: `install_skill` is the escalation path from chat
// access to arbitrary local execution and is documented as admin-only.
- // Plugin tools are owner-installed code, so members don't get them either.
+ // Plugin and MCP tools are owner-installed, so members don't get them either.
if (this.permissions.getCurrentSenderRole() === 'member') {
const filtered: Record<string, Tool> = {};
for (const [name, tool] of Object.entries(this.tools)) {
@@ -330,7 +346,8 @@ export class CapabilityRegistry {
}
return filtered;
}
- return this.withPluginTools(this.tools, false);
+ // MCP tools sit beside the built-ins (members never get them: above).
+ return this.withPluginTools(this.allTools(), false);
}
/**
@@ -368,7 +385,7 @@ export class CapabilityRegistry {
}
getToolNames(): string[] {
- return Object.keys(this.tools);
+ return Object.keys(this.allTools());
}
getSkillContext(): string {
diff --git a/src/capabilities/scheduler/schedule-task.ts b/src/capabilities/scheduler/schedule-task.ts
index dff20073..05e514a5 100644
--- a/src/capabilities/scheduler/schedule-task.ts
+++ b/src/capabilities/scheduler/schedule-task.ts
@@ -32,7 +32,12 @@ export function createScheduleTaskTool(scheduler: Scheduler, permissions: Permis
const allowTools = [...new Set((allow_tools ?? []).filter((t) => isPluginToolName(t)))];
const rejected = (allow_tools ?? []).filter((t) => !isPluginToolName(t));
- if (rejected.length) return `allow_tools only takes plugin tools (like whatsapp__call_owner); not: ${rejected.join(', ')}.`;
+ if (rejected.length) {
+ const mcpNote = rejected.some((t) => t.startsWith('mcp__'))
+ ? ' MCP tools run unattended only when the owner lists them in that server\'s tools.autoApprove (mercury.yaml).'
+ : '';
+ return `allow_tools only takes plugin tools (like whatsapp__call_owner); not: ${rejected.join(', ')}.${mcpNote}`;
+ }
if (allowTools.length && permissions.getCurrentSenderRole() === 'member') {
return 'Only the owner can schedule tasks that act without asking (allow_tools).';
}
diff --git a/src/core/commands/chat-command.ts b/src/core/commands/chat-command.ts
index 8df771d3..d9a5e296 100644
--- a/src/core/commands/chat-command.ts
+++ b/src/core/commands/chat-command.ts
@@ -50,6 +50,7 @@ import { PLAYER_CONTROLS, handlePlayerAction, formatNowPlaying } from '../../spo
import { getCloudTokenStore } from '../../cloud/token-store.js';
import { publishStatus, updateCliProviderStatus } from '../provider-status.js';
import { whatsNewText } from '../../utils/whats-new.js';
+import { formatMcpChatStatus } from '../../capabilities/mcp/admin.js';
import { FORGET_THAT_RE, MEMORY_SUBCOMMAND_HELP, handleBeliefCommand } from './memory-commands.js';
/**
@@ -1022,6 +1023,11 @@ export async function handleChatCommand(agent: Agent, content: string, channelTy
return true;
}
+ if (cmd === '/mcp' || cmd.startsWith('/mcp ')) {
+ await channel.send(formatMcpChatStatus(ctx.mcpStatus?.() ?? [], trimmed.slice('/mcp'.length).trim()), channelId);
+ return true;
+ }
+
if (cmd === '/skills' || cmd.startsWith('/skills ')) {
await agent.handleSkillsSlashCommand(trimmed, channel, channelId, ctx);
return true;
diff --git a/src/index.ts b/src/index.ts
index c8c66c39..42f1445e 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -91,9 +91,24 @@ import { selectWithArrowKeys } from './utils/arrow-select.js';
import { ProviderModelFetchError, fetchProviderModelCatalog } from './utils/provider-models.js';
import { initCloudTokenStore } from './cloud/token-store.js';
import { clearCloudRuntimeOnline, markCloudRuntimeOnline } from './cloud/runtime-status.js';
-import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler } from './web/server.js';
+import { startWebServer, stopWebServer, updateStatus as updateWebStatus, setUserMemory as setWebUserMemory, setWebChannel as setWebWebChannel, setScheduler as setWebScheduler, setAgentSupervisor as setWebSupervisor, setBackgroundTaskManager as setWebBgTasks, setSpotifyClient as setWebSpotify, setProgrammingMode as setWebProgrammingMode, setModelSwitchCallback as setWebModelSwitch, setCurrentProviderCallback as setWebCurrentProvider, setStatusSnapshotCallback as setWebStatusSnapshot, setKanbanSupervisor as setWebKanban, setKanbanBoardManager as setWebBoardManager, setKanbanProviders as setWebKanbanProviders, setIDEProviders as setWebIDEProviders, setSessionRepository as setWebSessions, setSessionSyncEnabledCallback as setWebSessionSyncEnabled, setBotManager as setWebBotManager, setBotsWebhookSecret, setShutdownHandler, setMcpManager as setWebMcpManager } from './web/server.js';
import { isWebAuthInitialized, setWebPassword, writeAttachToken } from './web/auth.js';
import { startLoopLagMonitor } from './utils/loop-lag.js';
+import { McpManager, probeMcpServer, validateMcpConfig, type McpServerStatus } from './capabilities/mcp/index.js';
+import {
+ addServer as addMcpServer,
+ allowTools as allowMcpTools,
+ buildServerConfig as buildMcpServerConfig,
+ disallowTools as disallowMcpTools,
+ formatServerList as formatMcpServerList,
+ formatStatusLine as formatMcpStatusLine,
+ formatStdioCommand as formatMcpStdioCommand,
+ formatToolLines as formatMcpToolLines,
+ getServer as getMcpServer,
+ removeServer as removeMcpServer,
+ setServerEnabled as setMcpServerEnabled,
+} from './capabilities/mcp/admin.js';
+import { runMcpDoctor, summarizeMcpConfig } from './capabilities/mcp/doctor.js';
const __dirname = dirname(fileURLToPath(import.meta.url));
let pkgVersion: string;
@@ -2611,6 +2626,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
memoryGetSubconscious: (limit?: number) => userMemory ? userMemory.getSubconscious(limit) : [],
memoryIsShareLearning: () => userMemory ? userMemory.isShareLearning() : false,
memorySetShareLearning: (enabled: boolean) => { if (userMemory) userMemory.setShareLearning(enabled); },
+ mcpStatus: () => capabilities.getMcpManager()?.status() ?? [],
});
capabilities.setSendFileHandler(async (filePath: string, channel?: string) => {
@@ -2683,6 +2699,20 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
capabilities.registerAll();
+ const mcpConfig = validateMcpConfig(config.mcp);
+ for (const problem of mcpConfig.problems) logger.warn({ problem }, 'MCP server skipped');
+ for (const warning of mcpConfig.warnings) logger.warn({ warning }, 'MCP config warning');
+ // Like plugins (ADR-025), only the runtime owner connects MCP servers: a
+ // terminal attached to a live daemon must not start every stdio server twice.
+ const mcpManager = daemonOwnsRuntime ? undefined : new McpManager(mcpConfig.servers, {
+ gate: (request) => capabilities.permissions.checkMcpTool(request),
+ });
+ if (mcpManager) {
+ capabilities.attachMcp(mcpManager);
+ setWebMcpManager(mcpManager);
+ void mcpManager.connectAll();
+ }
+
const agent = new Agent(
config, providers, identity, shortTerm, longTerm, episodic, userMemory, channels, tokenBudget, capabilities, scheduler, sessions,
async ({ userMessage, assistantMessage, providerName }) => {
@@ -3863,6 +3893,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {
// Release the bots' SQLite queue handle — on Windows an open handle
// keeps queue.db locked against any later uninstall/replace.
try { botManager?.dispose(); } catch { /* best effort */ }
+ try { await mcpManager?.close(); } catch { /* best effort */ }
try { await pluginManager?.shutdown(); } catch { /* best effort */ }
await agent.shutdown();
clearCloudRuntimeOnline();
@@ -4104,6 +4135,7 @@ program
.description('Reconfigure Mercury setup (name, providers, channels, permissions defaults)')
.option('--platform', 'Show platform compatibility diagnostics')
.option('--storage', 'Show SQLite backend, database files and row counts')
+ .option('--mcp', 'Connect to each configured MCP server and report its status')
.option('--plugins', 'Check installed plugins and why any are turned off')
.action(async (opts) => {
{
@@ -4120,6 +4152,14 @@ program
runStorageDoctor();
return;
}
+ if (opts.mcp) {
+ const mcpDoctor = await runMcpDoctor(loadConfig().mcp);
+ for (const line of mcpDoctor.lines) console.log(line);
+ if (!mcpDoctor.ok) process.exitCode = 1;
+ return;
+ }
+ const mcpSummary = summarizeMcpConfig(loadConfig().mcp);
+ if (mcpSummary) console.log(chalk.dim(` ${mcpSummary}`));
if (opts.plugins) {
const { runPluginDoctor } = await import('./cli/plugins-cli.js');
await runPluginDoctor();
@@ -5195,6 +5235,190 @@ program
console.log('');
});
+interface McpAddOptions {
+ stdio?: string;
+ http?: string;
+ env: string[];
+ header: string[];
+ cwd?: string;
+ allow?: string;
+ autoApprove?: string;
+ allowPrivate?: boolean;
+ disabled?: boolean;
+ yes?: boolean;
+}
+
+async function confirmMcp(question: string): Promise<boolean> {
+ try {
+ const answer = (await ask(chalk.white(` ${question} [y/N] `))).trim().toLowerCase();
+ return answer === 'y' || answer === 'yes';
+ } catch (err) {
+ if (err instanceof InputClosedError) return false;
+ throw err;
+ }
+}
+
+function printMcpProbe(status: McpServerStatus): void {
+ const line = formatMcpStatusLine(status);
+ console.log(status.state === 'connected' ? chalk.green(` ✓ ${line}`) : chalk.red(` ✗ ${line}`));
+ if (status.state === 'connected') {
+ for (const toolLine of formatMcpToolLines(status)) console.log(chalk.dim(` ${toolLine}`));
+ }
+ if (status.stderrTail) {
+ console.log(chalk.dim(' stderr:'));
+ for (const stderrLine of status.stderrTail.trim().split('\n').slice(-20)) console.log(chalk.dim(` ${stderrLine}`));
+ }
+}
+
+function mcpAction<A extends unknown[]>(fn: (...args: A) => Promise<void> | void): (...args: A) => Promise<void> {
+ return async (...args: A) => {
+ try {
+ await fn(...args);
+ } catch (err) {
+ console.log(chalk.red(` ${err instanceof Error ? err.message : String(err)}`));
+ console.log('');
+ process.exitCode = 1;
+ }
+ };
+}
+
+function saveMcpChange(config: MercuryConfig, message: string): void {
+ saveConfig(config);
+ console.log(chalk.green(` ✓ ${message}`));
+ restartDaemonIfRunning('Restarting the background daemon to apply the change...');
+ console.log('');
+}
+
+const collectRepeated = (value: string, previous: string[]): string[] => [...previous, value];
+
+const mcpCmd = program.command('mcp').description('Manage MCP servers whose tools Mercury can use');
+
+mcpCmd
+ .command('list')
+ .description('Show configured MCP servers')
+ .action(mcpAction(() => {
+ console.log('');
+ for (const line of formatMcpServerList(loadConfig())) {
+ console.log(line.startsWith(' ') ? chalk.dim(` ${line}`) : ` ${line}`);
+ }
+ console.log('');
+ }));
+
+mcpCmd
+ .command('add <id> [args...]')
+ .description('Add an MCP server: --stdio <command> [-- args...] or --http <url>')
+ .option('--stdio <command>', 'command that starts a local stdio server')
+ .option('--http <url>', 'Streamable HTTP endpoint of a remote server')
+ .option('--env <KEY=VALUE>', 'environment variable for a stdio server, ${env:NAME} for secrets (repeatable)', collectRepeated, [])
+ .option('--header <Name: value>', 'HTTP header, ${env:NAME} for secrets (repeatable)', collectRepeated, [])
+ .option('--cwd <dir>', 'working directory for a stdio server')
+ .option('--allow <tools>', 'comma-separated tools the agent may see, or *')
+ .option('--auto-approve <tools>', 'comma-separated tools that run without asking')
+ .option('--allow-private', 'allow a private or loopback address for an HTTP server')
+ .option('--disabled', 'save the server without enabling it')
+ .option('-y, --yes', 'do not ask for confirmation')
+ .action(mcpAction(async (id: string, args: string[], opts: McpAddOptions) => {
+ const config = loadConfig();
+ const server = buildMcpServerConfig({ ...opts, args });
+ const warnings = addMcpServer(config, id, server);
+ console.log('');
+ for (const warning of warnings) console.log(chalk.yellow(` ⚠ ${warning}`));
+ if (server.transport === 'stdio') {
+ console.log(chalk.white(` Mercury will start this command: ${formatMcpStdioCommand(server)}`));
+ if (!opts.yes && !(await confirmMcp('Add this server?'))) {
+ console.log(chalk.dim(' Cancelled.'));
+ console.log('');
+ return;
+ }
+ }
+ if (server.enabled !== false) {
+ console.log(chalk.dim(' Testing the connection...'));
+ const status = await probeMcpServer(id, server);
+ printMcpProbe(status);
+ if (status.state !== 'connected' && !opts.yes && !(await confirmMcp('Save it anyway?'))) {
+ console.log(chalk.dim(' Cancelled.'));
+ console.log('');
+ return;
+ }
+ }
+ if (!server.tools?.allow?.length) {
+ console.log(chalk.dim(` No tools are enabled yet. Enable some with \`mercury mcp allow ${id} <tool...>\`.`));
+ }
+ saveMcpChange(config, `MCP server "${id}" saved.`);
+ }));
+
+mcpCmd
+ .command('remove <id>')
+ .description('Remove an MCP server')
+ .action(mcpAction((id: string) => {
+ const config = loadConfig();
+ removeMcpServer(config, id);
+ console.log('');
+ saveMcpChange(config, `MCP server "${id}" removed.`);
+ }));
+
+mcpCmd
+ .command('enable <id>')
+ .description('Enable an MCP server')
+ .option('-y, --yes', 'do not ask for confirmation')
+ .action(mcpAction(async (id: string, opts: { yes?: boolean }) => {
+ const config = loadConfig();
+ const server = getMcpServer(config, id);
+ console.log('');
+ if (server.transport === 'stdio') {
+ console.log(chalk.white(` Mercury will start this command: ${formatMcpStdioCommand(server)}`));
+ if (!opts.yes && !(await confirmMcp('Enable this server?'))) {
+ console.log(chalk.dim(' Cancelled.'));
+ console.log('');
+ return;
+ }
+ }
+ setMcpServerEnabled(config, id, true);
+ saveMcpChange(config, `MCP server "${id}" enabled.`);
+ }));
+
+mcpCmd
+ .command('disable <id>')
+ .description('Disable an MCP server without removing it')
+ .action(mcpAction((id: string) => {
+ const config = loadConfig();
+ setMcpServerEnabled(config, id, false);
+ console.log('');
+ saveMcpChange(config, `MCP server "${id}" disabled.`);
+ }));
+
+mcpCmd
+ .command('allow <id> <tools...>')
+ .description('Let the agent see these tools (quote "*" to allow all)')
+ .action(mcpAction((id: string, tools: string[]) => {
+ const config = loadConfig();
+ const server = allowMcpTools(config, id, tools);
+ console.log('');
+ saveMcpChange(config, `${id}: allowed ${server.tools?.allow?.join(', ') || 'nothing'}.`);
+ }));
+
+mcpCmd
+ .command('disallow <id> <tools...>')
+ .description('Hide these tools from the agent')
+ .action(mcpAction((id: string, tools: string[]) => {
+ const config = loadConfig();
+ const server = disallowMcpTools(config, id, tools);
+ console.log('');
+ const deny = server.tools?.deny?.length ? `, denied ${server.tools.deny.join(', ')}` : '';
+ saveMcpChange(config, `${id}: allowed ${server.tools?.allow?.join(', ') || 'nothing'}${deny}.`);
+ }));
+
+mcpCmd
+ .command('test <id>')
+ .description('Connect to an MCP server and list its tools')
+ .action(mcpAction(async (id: string) => {
+ const server = getMcpServer(loadConfig(), id);
+ console.log('');
+ const status = await probeMcpServer(id, server);
+ printMcpProbe(status);
+ console.log('');
+ if (status.state !== 'connected') process.exitCode = 1;
+ }));
registerPluginsCli(program);
const cloud = program.command('cloud').description('Manage Mercury Cloud connection');
diff --git a/src/plugins/tool-bridge.ts b/src/plugins/tool-bridge.ts
index fa5d670d..aefdf265 100644
--- a/src/plugins/tool-bridge.ts
+++ b/src/plugins/tool-bridge.ts
@@ -11,6 +11,7 @@
* contain "__", so the name alone identifies a plugin tool.
*/
import { jsonSchema, tool, type Tool } from 'ai';
+import { isMcpToolName } from '../capabilities/mcp/naming.js';
import type { PermissionManager } from '../capabilities/permissions.js';
import { logger } from '../utils/logger.js';
@@ -101,13 +102,14 @@ export function pluginToolName(pluginId: string, name: string): string {
/** True for any name shaped like a plugin tool, live or not. */
export function isPluginToolName(name: string): boolean {
- return TOOL_NAME_RE.test(name);
+ // `mcp__<server>__<tool>` has the same shape but is an MCP tool (ADR-029).
+ return !isMcpToolName(name) && TOOL_NAME_RE.test(name);
}
/** A bot may use a plugin tool only when its allow list names it, or the whole plugin ("<id>__*"). */
export function pluginToolAllowed(name: string, allow: readonly string[]): boolean {
const m = TOOL_NAME_RE.exec(name);
- if (!m) return false;
+ if (!m || isMcpToolName(name)) return false;
return allow.includes(name) || allow.includes(`${m[1]}__*`);
}
diff --git a/src/plugins/types.ts b/src/plugins/types.ts
index 33416135..bd1793c6 100644
--- a/src/plugins/types.ts
+++ b/src/plugins/types.ts
@@ -29,6 +29,8 @@ export const PLUGIN_API_VERSION = '1.2.0';
export const PLUGIN_ID_RE = /^[a-z][a-z0-9-]{1,30}[a-z0-9]$/;
/** Tool and command names a plugin declares (before namespacing). */
export const PLUGIN_TOOL_NAME_RE = /^[a-z][a-z0-9_]{0,29}$/;
+/** Ids a plugin can't take: `mcp` tools are named `mcp__<server>__<tool>` (ADR-029). */
+export const RESERVED_PLUGIN_IDS: ReadonlySet<string> = new Set(['mcp']);
/**
* Built-in command names a plugin can never take. Kept in sync with the
* TUI's SLASH_COMMANDS by src/plugins/commands.test.ts.
@@ -38,7 +40,7 @@ export const RESERVED_COMMANDS: ReadonlySet<string> = new Set([
'permissions', 'plugin', 'plugins', 'progress', 'research', 'reset', 'saver', 'session', 'sessions', 'skills', 'spotify',
'status', 'stop', 'stream', 'tools', 'update', 'view', 'whatsnew', 'ws', 'start', 'skip', 'new', 'compact', 'clear',
'approve', 'deny', 'yes', 'no', 'cancel', 'pair', 'unpair', 'telegram', 'discord', 'slack', 'signal', 'web', 'exit', 'quit',
- 'usage', 'cost', 'doctor', 'settings', 'config', 'login', 'logout', 'upgrade', 'version', 'about',
+ 'usage', 'cost', 'doctor', 'settings', 'config', 'login', 'logout', 'upgrade', 'version', 'about', 'mcp',
]);
/** Mercury providers a plugin can ask to use (Plugin API 1.1). */
@@ -150,7 +152,8 @@ const serverSpec = z.object({
export const manifestSchema = z.object({
manifestVersion: z.literal(MANIFEST_VERSION),
- id: z.string().regex(PLUGIN_ID_RE, '3-32 characters: lowercase letters, digits and hyphens, starting with a letter'),
+ id: z.string().regex(PLUGIN_ID_RE, '3-32 characters: lowercase letters, digits and hyphens, starting with a letter')
+ .refine((id) => !RESERVED_PLUGIN_IDS.has(id), (id) => ({ message: `"${id}" is reserved by Mercury` })),
name: z.string().min(1).max(60),
version: strictSemver,
description: z.string().min(1).max(280),
@@ -389,7 +392,7 @@ const catalogArtifact = z.object({
}).strict();
export const catalogEntrySchema = z.object({
- id: z.string().regex(PLUGIN_ID_RE),
+ id: z.string().regex(PLUGIN_ID_RE).refine((id) => !RESERVED_PLUGIN_IDS.has(id)),
name: z.string().min(1).max(60),
description: z.string().min(1).max(280),
version: strictSemver,
diff --git a/src/ui/input-composer.tsx b/src/ui/input-composer.tsx
index 93c18938..46c12482 100644
--- a/src/ui/input-composer.tsx
+++ b/src/ui/input-composer.tsx
@@ -119,6 +119,8 @@ export const SLASH_COMMANDS: readonly string[] = [
'/halt',
'/reset',
'/tools',
+ '/mcp',
+ '/mcp tools ',
'/skills',
'/skills search ',
'/skills view ',
diff --git a/src/utils/config.ts b/src/utils/config.ts
index 66c7d967..f10e8f54 100644
--- a/src/utils/config.ts
+++ b/src/utils/config.ts
@@ -5,6 +5,7 @@ import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
import { config as loadDotenv } from 'dotenv';
import { logger } from './logger.js';
import type { SignalAccessUser, SignalPendingRequest, DiscordAccessUser, DiscordPendingRequest, SlackAccessUser, SlackPendingRequest } from '../types/channel.js';
+import type { McpConfig } from '../capabilities/mcp/types.js';
import {
LEGACY_SEED_API_URL,
LEGACY_SEED_WS_URL,
@@ -275,6 +276,7 @@ export interface MercuryConfig {
enabled: boolean;
port: number;
};
+ mcp?: McpConfig;
}
function getEnv(key: string, fallback: string = ''): string {
diff --git a/src/utils/manual.ts b/src/utils/manual.ts
index 61c54e93..fc15b072 100644
--- a/src/utils/manual.ts
+++ b/src/utils/manual.ts
@@ -146,6 +146,8 @@ export function getManual(): string {
['/telegram demote <id>', 'CLI chat only: demote a Telegram admin to member'],
['/telegram reset', 'CLI chat only: reset all Telegram access'],
['/tools', 'List currently loaded tools'],
+ ['/mcp', 'Show MCP servers and whether they are connected'],
+ ['/mcp tools <server>', 'List the tools of an MCP server and which ones the agent may use'],
['/skills', 'List installed skills'],
['/skills search <query>', 'Search skills.mercuryagent.sh'],
['/skills view <id>', 'Show details + registry URL for a skill'],
diff --git a/src/utils/redact.test.ts b/src/utils/redact.test.ts
index c4a5c6fc..64de020e 100644
--- a/src/utils/redact.test.ts
+++ b/src/utils/redact.test.ts
@@ -3,9 +3,18 @@ import { describe, expect, it } from 'vitest';
// Secret-shaped fixtures are assembled at runtime: contiguous literals in
// this file would trip GitHub push protection's secret scanner.
const join = (...parts: string[]) => parts.join('');
-import { redactSecrets, redactDeep } from './redact.js';
+import { redactSecrets, redactDeep, registerSecretValue } from './redact.js';
describe('secret redaction', () => {
+ it('masks registered secret values wherever they appear', () => {
+ const secret = join('plain-registered-', 'value-0042');
+ expect(redactSecrets(`token is ${secret}.`)).toBe(`token is ${secret}.`);
+ registerSecretValue(secret);
+ expect(redactSecrets(`token is ${secret}, again ${secret}`)).toBe('token is ****, again ****');
+ registerSecretValue('short');
+ expect(redactSecrets('a short word')).toBe('a short word');
+ });
+
it('masks API keys while keeping a recognizable prefix/suffix', () => {
const out = redactSecrets(join('export OPENAI_API_KEY=sk-proj-', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '1234567890abcd'));
expect(out).not.toContain('ABCDEFGHIJKLMNOPQRSTUVWXYZ');
diff --git a/src/utils/redact.ts b/src/utils/redact.ts
index f382097d..8e2341c8 100644
--- a/src/utils/redact.ts
+++ b/src/utils/redact.ts
@@ -47,9 +47,18 @@ function maskMatch(match: string): string {
return `${match.slice(0, 4)}****${match.slice(-4)}`;
}
+const registeredSecrets = new Set<string>();
+
+export function registerSecretValue(value: string): void {
+ if (typeof value === 'string' && value.length >= 8) registeredSecrets.add(value);
+}
+
export function redactSecrets(text: string): string {
if (!text) return text;
let out = text;
+ for (const secret of registeredSecrets) {
+ if (out.includes(secret)) out = out.split(secret).join('****');
+ }
for (const pattern of SECRET_PATTERNS) {
out = out.replace(pattern, maskMatch);
}
diff --git a/src/utils/ssrf-guarded-fetch.test.ts b/src/utils/ssrf-guarded-fetch.test.ts
new file mode 100644
index 00000000..7ffd0edd
--- /dev/null
+++ b/src/utils/ssrf-guarded-fetch.test.ts
@@ -0,0 +1,89 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest';
+import { createServer, type Server } from 'node:http';
+import type { AddressInfo } from 'node:net';
+import { createGuardedFetch, PinTable } from './ssrf.js';
+
+let server: Server;
+let base: string;
+
+beforeAll(async () => {
+ server = createServer((req, res) => {
+ if (req.url === '/redirect') {
+ res.writeHead(302, { location: '/echo' }).end();
+ return;
+ }
+ let body = '';
+ req.on('data', (chunk) => (body += chunk));
+ req.on('end', () => {
+ res
+ .writeHead(200, { 'content-type': 'application/json' })
+ .end(JSON.stringify({ method: req.method, body, auth: req.headers.authorization ?? null }));
+ });
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ base = `http://127.0.0.1:${(server.address() as AddressInfo).port}`;
+});
+
+afterAll(() => {
+ server.close();
+});
+
+describe('createGuardedFetch', () => {
+ it('blocks loopback targets by default', async () => {
+ await expect(createGuardedFetch()(`${base}/echo`)).rejects.toThrow(
+ /private\/internal address \(SSRF protection\)\. Set MERCURY_ALLOW_PRIVATE_FETCH=1/,
+ );
+ });
+
+ it('uses the caller hint when a target is blocked', async () => {
+ await expect(createGuardedFetch({ privateHint: 'Use the server setting.' })(`${base}/echo`)).rejects.toThrow(
+ 'Blocked: 127.0.0.1 is a private/internal address (SSRF protection). Use the server setting.',
+ );
+ });
+
+ it('forwards method, body and headers when private targets are allowed', async () => {
+ const res = await createGuardedFetch({ allowPrivate: true })(new URL(`${base}/echo`), {
+ method: 'POST',
+ body: '{"x":1}',
+ headers: { authorization: 'Bearer abc' },
+ });
+ expect(await res.json()).toEqual({ method: 'POST', body: '{"x":1}', auth: 'Bearer abc' });
+ });
+
+ it('returns redirects instead of following them', async () => {
+ const res = await createGuardedFetch({ allowPrivate: true })(`${base}/redirect`);
+ expect(res.status).toBe(302);
+ expect(res.headers.get('location')).toBe('/echo');
+ });
+
+ it('still rejects non-http schemes', async () => {
+ await expect(createGuardedFetch({ allowPrivate: true })('file:///etc/passwd')).rejects.toThrow(/Blocked scheme/);
+ // allowPrivate opens loopback and the LAN, never cloud metadata.
+ await expect(createGuardedFetch({ allowPrivate: true })('http://169.254.169.254/latest/meta-data/')).rejects.toThrow(/link-local/);
+ await expect(createGuardedFetch({ allowPrivate: true })('http://[fe80::1]/')).rejects.toThrow(/link-local/);
+ await expect(createGuardedFetch({ allowPrivate: true })('http://metadata.google.internal/')).rejects.toThrow(/metadata/);
+ });
+});
+
+describe('PinTable', () => {
+ it('keeps a host pinned until every request using it has finished', () => {
+ const pins = new PinTable();
+ pins.acquire('example.com', { address: '93.184.216.34', family: 4 });
+ pins.acquire('example.com', { address: '93.184.216.34', family: 4 });
+ pins.release('example.com');
+ expect(pins.get('example.com')).toEqual({ address: '93.184.216.34', family: 4 });
+ pins.release('example.com');
+ expect(pins.get('example.com')).toBeUndefined();
+ pins.release('example.com');
+ expect(pins.get('example.com')).toBeUndefined();
+ });
+
+ it('uses the latest validated address while requests overlap', () => {
+ const pins = new PinTable();
+ pins.acquire('example.com', { address: '93.184.216.34', family: 4 });
+ pins.acquire('example.com', { address: '93.184.216.35', family: 4 });
+ expect(pins.get('example.com')).toEqual({ address: '93.184.216.35', family: 4 });
+ pins.release('example.com');
+ expect(pins.get('example.com')).toEqual({ address: '93.184.216.35', family: 4 });
+ });
+});
diff --git a/src/utils/ssrf.ts b/src/utils/ssrf.ts
index 54246847..f0c4c26c 100644
--- a/src/utils/ssrf.ts
+++ b/src/utils/ssrf.ts
@@ -62,6 +62,21 @@ function isPrivateIpv6(ip: string): boolean {
return false;
}
+/**
+ * Link-local addresses, where cloud metadata services live (169.254.169.254,
+ * fd00:ec2::254 is unique-local and stays private). `allowPrivate` opens
+ * loopback and the LAN, never these: a metadata endpoint hands out the
+ * machine's cloud credentials.
+ */
+export function isLinkLocalAddress(ip: string): boolean {
+ const lower = ip.toLowerCase();
+ const v4 = lower.startsWith('::ffff:') ? lower.slice('::ffff:'.length) : lower;
+ if (isIP(v4) === 4) return v4.startsWith('169.254.');
+ return isIP(lower) === 6 && /^fe[89ab]/.test(lower.split(':')[0] ?? '');
+}
+
+const METADATA_HOSTS = new Set(['metadata.google.internal', 'metadata', 'instance-data', 'instance-data.ec2.internal']);
+
export function isPrivateAddress(ip: string): boolean {
const family = isIP(ip);
if (family === 4) return isPrivateIpv4(ip);
@@ -77,11 +92,10 @@ function urlHostIsPrivate(hostname: string): boolean {
return false;
}
-function privateBlockReason(host: string): Error {
- return new Error(
- `Blocked: ${host} is a private/internal address (SSRF protection). ` +
- 'Set MERCURY_ALLOW_PRIVATE_FETCH=1 to allow fetching internal hosts.',
- );
+const DEFAULT_PRIVATE_HINT = 'Set MERCURY_ALLOW_PRIVATE_FETCH=1 to allow fetching internal hosts.';
+
+function privateBlockReason(host: string, hint = DEFAULT_PRIVATE_HINT): Error {
+ return new Error(`Blocked: ${host} is a private/internal address (SSRF protection). ${hint}`);
}
function lookupHost(hostname: string): Promise<string[]> {
@@ -99,7 +113,7 @@ function lookupHost(hostname: string): Promise<string[]> {
type PinnedAddress = { address: string; family: number };
type ResolvedTarget = { url: URL; pinned?: PinnedAddress };
-async function resolveAndValidate(rawUrl: string): Promise<ResolvedTarget> {
+async function resolveAndValidate(rawUrl: string, allowPrivate = false, privateHint?: string): Promise<ResolvedTarget> {
let parsed: URL;
try {
parsed = new URL(rawUrl);
@@ -109,8 +123,21 @@ async function resolveAndValidate(rawUrl: string): Promise<ResolvedTarget> {
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
throw new Error(`Blocked scheme: ${parsed.protocol} — only http and https are allowed`);
}
+ if (allowPrivate) {
+ // Loopback and the LAN are allowed; link-local (cloud metadata) never is.
+ const host = parsed.hostname.replace(/^\[|\]$/g, '').toLowerCase();
+ if (METADATA_HOSTS.has(host)) throw new Error(`Blocked: ${host} is a cloud metadata service`);
+ const literal = isIP(host);
+ if (literal !== 0) {
+ if (isLinkLocalAddress(host)) throw new Error(`Blocked: ${host} is link-local (cloud metadata)`);
+ return { url: parsed, pinned: { address: host, family: literal } };
+ }
+ const resolved = await lookupHost(host);
+ if (resolved.some(isLinkLocalAddress)) throw new Error(`Blocked: ${host} resolves to a link-local (cloud metadata) address`);
+ return { url: parsed, ...(resolved[0] ? { pinned: { address: resolved[0], family: isIP(resolved[0]) } } : {}) };
+ }
if (urlHostIsPrivate(parsed.hostname)) {
- throw privateBlockReason(parsed.hostname);
+ throw privateBlockReason(parsed.hostname, privateHint);
}
if (ALLOW_PRIVATE_FETCH) {
return { url: parsed };
@@ -129,7 +156,7 @@ async function resolveAndValidate(rawUrl: string): Promise<ResolvedTarget> {
// connection would have picked.
const offending = addresses.find((ip) => isPrivateAddress(ip));
if (offending) {
- throw privateBlockReason(parsed.hostname);
+ throw privateBlockReason(parsed.hostname, privateHint);
}
const chosen = addresses[0]!;
return { url: parsed, pinned: { address: chosen, family: isIP(chosen) } };
@@ -195,3 +222,56 @@ export async function guardedFetch(rawUrl: string, signal: AbortSignal, headers?
}
throw new Error('Blocked: too many redirects');
}
+
+export type GuardedFetchLike = (input: string | URL, init?: RequestInit) => Promise<Response>;
+
+export class PinTable {
+ private readonly pins = new Map<string, { pin: { address: string; family: number }; count: number }>();
+
+ acquire(host: string, pin: { address: string; family: number }): void {
+ const entry = this.pins.get(host);
+ this.pins.set(host, { pin, count: (entry?.count ?? 0) + 1 });
+ }
+
+ release(host: string): void {
+ const entry = this.pins.get(host);
+ if (!entry) return;
+ if (entry.count <= 1) this.pins.delete(host);
+ else entry.count -= 1;
+ }
+
+ get(host: string): { address: string; family: number } | undefined {
+ return this.pins.get(host)?.pin;
+ }
+}
+
+const guardedFetchPins = new PinTable();
+
+const guardedFetchAgent = new Agent({
+ connect: {
+ lookup: ((hostname: string, options: { all?: boolean } | undefined, callback: (...args: unknown[]) => void) => {
+ const pinned = guardedFetchPins.get(hostname);
+ if (!pinned) {
+ (lookup as unknown as (host: string, opts: unknown, cb: unknown) => void)(hostname, options, callback);
+ return;
+ }
+ if (options?.all) callback(null, [{ address: pinned.address, family: pinned.family }]);
+ else callback(null, pinned.address, pinned.family);
+ }) as never,
+ },
+});
+
+export function createGuardedFetch(options: { allowPrivate?: boolean; privateHint?: string } = {}): GuardedFetchLike {
+ return async (input, init = {}) => {
+ const href = typeof input === 'string' ? input : input.href;
+ const { url, pinned } = await resolveAndValidate(href, options.allowPrivate === true, options.privateHint);
+ const host = url.hostname;
+ if (pinned) guardedFetchPins.acquire(host, pinned);
+ try {
+ const guardedInit: FetchInitWithDispatcher = { ...init, redirect: 'manual', dispatcher: guardedFetchAgent };
+ return await fetch(url, guardedInit);
+ } finally {
+ if (pinned) guardedFetchPins.release(host);
+ }
+ };
+}
diff --git a/src/utils/tool-label.ts b/src/utils/tool-label.ts
index a9410ba8..f885162c 100644
--- a/src/utils/tool-label.ts
+++ b/src/utils/tool-label.ts
@@ -54,7 +54,8 @@ function truncate(maxLen: number): (v: string) => string {
export function formatToolStep(toolName: string, args: Record<string, any>): string {
const config = TOOL_LABELS[toolName];
if (!config) {
- return toolName;
+ const mcp = /^mcp__([a-z][a-z0-9-]*)__(.+)$/.exec(toolName);
+ return mcp ? `🔌 ${mcp[1]} › ${mcp[2]}` : toolName;
}
let detail = '';
diff --git a/src/web/api/mcp.test.ts b/src/web/api/mcp.test.ts
new file mode 100644
index 00000000..f9a165f1
--- /dev/null
+++ b/src/web/api/mcp.test.ts
@@ -0,0 +1,47 @@
+import { afterEach, describe, expect, it } from 'vitest';
+import app, { setMcpManager } from './mcp.js';
+import type { McpManager } from '../../capabilities/mcp/manager.js';
+import type { McpServerStatus } from '../../capabilities/mcp/types.js';
+
+const status: McpServerStatus = {
+ id: 'docs',
+ transport: 'http',
+ enabled: true,
+ state: 'failed',
+ target: 'https://mcp.example.com',
+ error: 'HTTP 401',
+ toolCount: 1,
+ tools: [{ name: 'search', exposedName: 'mcp__docs__search', allowed: true, autoApprove: false }],
+ stderrTail: 'server log line that must stay local',
+};
+
+afterEach(() => setMcpManager(null));
+
+describe('GET /api/mcp', () => {
+ it('reports no servers when MCP is not running in this process', async () => {
+ const res = await app.request('/api/mcp');
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual({ available: false, servers: [] });
+ });
+
+ it('returns only the public status fields', async () => {
+ setMcpManager({ status: () => [status] } as unknown as McpManager);
+ const body = await (await app.request('/api/mcp')).json();
+ expect(body).toEqual({
+ available: true,
+ servers: [
+ {
+ id: 'docs',
+ transport: 'http',
+ enabled: true,
+ state: 'failed',
+ target: 'https://mcp.example.com',
+ error: 'HTTP 401',
+ toolCount: 1,
+ tools: [{ name: 'search', exposedName: 'mcp__docs__search', allowed: true, autoApprove: false, skipped: null }],
+ },
+ ],
+ });
+ expect(JSON.stringify(body)).not.toContain('server log line');
+ });
+});
diff --git a/src/web/api/mcp.ts b/src/web/api/mcp.ts
new file mode 100644
index 00000000..52274485
--- /dev/null
+++ b/src/web/api/mcp.ts
@@ -0,0 +1,36 @@
+import { Hono } from 'hono';
+import type { McpManager } from '../../capabilities/mcp/manager.js';
+import type { McpServerStatus } from '../../capabilities/mcp/types.js';
+
+const mcp = new Hono();
+let manager: McpManager | null = null;
+
+export function setMcpManager(next: McpManager | null): void {
+ manager = next;
+}
+
+export function toPublicMcpStatus(status: McpServerStatus) {
+ return {
+ id: status.id,
+ transport: status.transport,
+ enabled: status.enabled,
+ state: status.state,
+ target: status.target,
+ error: status.error ?? null,
+ toolCount: status.toolCount,
+ tools: status.tools.map((tool) => ({
+ name: tool.name,
+ exposedName: tool.exposedName,
+ allowed: tool.allowed,
+ autoApprove: tool.autoApprove,
+ skipped: tool.skipped ?? null,
+ })),
+ };
+}
+
+mcp.get('/api/mcp', (c) => {
+ const servers = manager ? manager.status().map(toPublicMcpStatus) : [];
+ return c.json({ available: manager !== null, servers });
+});
+
+export default mcp;
diff --git a/src/web/server.ts b/src/web/server.ts
index 1602346c..08f55641 100644
--- a/src/web/server.ts
+++ b/src/web/server.ts
@@ -20,6 +20,7 @@ import spotifyRoutes, { setSpotifyClient } from './api/spotify.js';
import kanbanRoutes, { setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders } from './api/kanban.js';
import ideRoutes, { setIDEProviders } from './api/workspace-ide.js';
import lifecycleRoutes, { setShutdownHandler } from './api/lifecycle.js';
+import mcpRoutes, { setMcpManager } from './api/mcp.js';
import pluginRoutes from './api/plugins.js';
import { BoardManager } from '../core/board-manager.js';
import { isBetterSqlite3Available } from '../memory/second-brain-db.js';
@@ -84,6 +85,7 @@ app.route('/', spotifyRoutes);
app.route('/', kanbanRoutes);
app.route('/', ideRoutes);
app.route('/', lifecycleRoutes);
+app.route('/', mcpRoutes);
app.route('/', pluginRoutes);
// ── Legacy static assets (vendor fonts, icons, wasm — still needed by React SPA) ──
@@ -199,7 +201,7 @@ if (spaAvailable) {
});
}
-export { setShutdownHandler };
+export { setShutdownHandler, setMcpManager };
export { updateStatus, setUserMemory, setWebChannel, setScheduler, setAgentSupervisor, setBackgroundTaskManager, setSpotifyClient, setProgrammingMode, setModelSwitchCallback, setCurrentProviderCallback, setStatusSnapshotCallback, setKanbanSupervisor, setKanbanBoardManager, setKanbanProviders, setIDEProviders, setBotManager, setBotsWebhookSecret };
let webServer: ReturnType<typeof createAdaptorServer> | null = null;
diff --git a/ui/src/App.tsx b/ui/src/App.tsx
index 57721791..4ab9fb88 100644
--- a/ui/src/App.tsx
+++ b/ui/src/App.tsx
@@ -16,6 +16,7 @@ const GoalsPage = lazy(() => import("./pages/brain/Goals").then((m) => ({ defaul
const GraphPage = lazy(() => import("./pages/brain/Graph").then((m) => ({ default: m.GraphPage })));
const ProvidersPage = lazy(() => import("./pages/Providers").then((m) => ({ default: m.ProvidersPage })));
const SkillsPage = lazy(() => import("./pages/Skills").then((m) => ({ default: m.SkillsPage })));
+const McpPage = lazy(() => import("./pages/Mcp").then((m) => ({ default: m.McpPage })));
const PluginsPage = lazy(() => import("./pages/Plugins").then((m) => ({ default: m.PluginsPage })));
const PermissionsPage = lazy(() => import("./pages/Permissions").then((m) => ({ default: m.PermissionsPage })));
const SchedulesPage = lazy(() => import("./pages/Schedules").then((m) => ({ default: m.SchedulesPage })));
@@ -79,6 +80,7 @@ function AnimatedRoutes() {
<Route path="second-brain/graph" element={<AnimatedPage><GraphPage /></AnimatedPage>} />
<Route path="providers" element={<AnimatedPage><ProvidersPage /></AnimatedPage>} />
<Route path="skills" element={<AnimatedPage><SkillsPage /></AnimatedPage>} />
+ <Route path="mcp" element={<AnimatedPage><McpPage /></AnimatedPage>} />
<Route path="plugins" element={<AnimatedPage><PluginsPage /></AnimatedPage>} />
<Route path="permissions" element={<AnimatedPage><PermissionsPage /></AnimatedPage>} />
<Route path="schedules" element={<AnimatedPage><SchedulesPage /></AnimatedPage>} />
diff --git a/ui/src/components/layout/Sidebar.tsx b/ui/src/components/layout/Sidebar.tsx
index 77b01f67..70360bd4 100644
--- a/ui/src/components/layout/Sidebar.tsx
+++ b/ui/src/components/layout/Sidebar.tsx
@@ -16,6 +16,7 @@ import {
Cpu,
Bot,
Puzzle,
+ Plug,
Blocks,
Shield,
Clock,
@@ -64,6 +65,7 @@ const NAV_SECTIONS = [
items: [
{ to: "/providers", icon: Cpu, label: "Providers" },
{ to: "/skills", icon: Puzzle, label: "Skills" },
+ { to: "/mcp", icon: Plug, label: "MCP" },
{ to: "/plugins", icon: Blocks, label: "Plugins" },
{ to: "/permissions", icon: Shield, label: "Permissions" },
{ to: "/schedules", icon: Clock, label: "Schedules" },
diff --git a/ui/src/lib/api.ts b/ui/src/lib/api.ts
index 233a66d7..d78e0d3d 100644
--- a/ui/src/lib/api.ts
+++ b/ui/src/lib/api.ts
@@ -384,6 +384,10 @@ export const usage = {
};
// ── Schedules ──
+export const mcp = {
+ list: () => get<{ available: boolean; servers: McpServer[] }>("/api/mcp"),
+};
+
export const schedules = {
list: () => get<{ schedules: Schedule[]; total: number }>("/api/schedules"),
update: (id: string, data: Partial<Schedule>) =>
@@ -923,6 +927,25 @@ export interface UsageData {
byChannel: Record<string, number>;
}
+export interface McpTool {
+ name: string;
+ exposedName: string;
+ allowed: boolean;
+ autoApprove: boolean;
+ skipped: string | null;
+}
+
+export interface McpServer {
+ id: string;
+ transport: "stdio" | "http";
+ enabled: boolean;
+ state: "disabled" | "connecting" | "connected" | "reconnecting" | "failed";
+ target: string;
+ error: string | null;
+ toolCount: number;
+ tools: McpTool[];
+}
+
export interface Schedule {
id: string;
description: string;
@@ -1046,6 +1069,7 @@ const api = {
permissions,
usage,
schedules,
+ mcp,
spotify,
boards,
bots: {
diff --git a/ui/src/pages/Mcp.tsx b/ui/src/pages/Mcp.tsx
new file mode 100644
index 00000000..901abd90
--- /dev/null
+++ b/ui/src/pages/Mcp.tsx
@@ -0,0 +1,124 @@
+import { useCallback, useEffect, useState } from "react";
+import { motion } from "framer-motion";
+import { Plug, RefreshCw } from "lucide-react";
+import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
+import { Badge } from "@/components/ui/badge";
+import { Button } from "@/components/ui/button";
+import { cn } from "@/lib/utils";
+import api, { type McpServer, type McpTool } from "@/lib/api";
+
+const STATE_STYLES: Record<McpServer["state"], string> = {
+ connected: "border-emerald-500/30 bg-emerald-500/10 text-emerald-500",
+ connecting: "border-sky-500/30 bg-sky-500/10 text-sky-500",
+ reconnecting: "border-amber-500/30 bg-amber-500/10 text-amber-500",
+ failed: "border-destructive/30 bg-destructive/10 text-destructive",
+ disabled: "border-border bg-muted text-muted-foreground",
+};
+
+function toolState(tool: McpTool): { label: string; className: string } {
+ if (tool.skipped) return { label: "skipped", className: "text-amber-500" };
+ if (!tool.allowed) return { label: "hidden", className: "text-muted-foreground" };
+ if (tool.autoApprove) return { label: "auto-approve", className: "text-emerald-500" };
+ return { label: "asks first", className: "text-foreground" };
+}
+
+export function McpPage() {
+ const [servers, setServers] = useState<McpServer[]>([]);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState("");
+
+ const load = useCallback(() => {
+ setLoading(true);
+ api.mcp
+ .list()
+ .then((res) => {
+ setServers(res.servers);
+ setError("");
+ })
+ .catch((err: Error) => setError(err.message))
+ .finally(() => setLoading(false));
+ }, []);
+
+ useEffect(() => {
+ load();
+ }, [load]);
+
+ return (
+ <div className="space-y-6 p-6 lg:p-8">
+ <motion.div
+ initial={{ opacity: 0, y: -8 }}
+ animate={{ opacity: 1, y: 0 }}
+ transition={{ duration: 0.3 }}
+ className="flex flex-wrap items-start justify-between gap-4"
+ >
+ <div>
+ <h1 className="text-2xl font-bold tracking-tight">MCP Servers</h1>
+ <p className="text-sm text-muted-foreground">
+ Read-only. Add or change servers with <code className="font-mono">mercury mcp</code> in a terminal.
+ </p>
+ </div>
+ <Button variant="outline" size="sm" onClick={load} disabled={loading}>
+ <RefreshCw className={cn("mr-2 h-4 w-4", loading && "animate-spin")} />
+ Refresh
+ </Button>
+ </motion.div>
+
+ {error && <p className="text-sm text-destructive">{error}</p>}
+
+ {!loading && !error && servers.length === 0 && (
+ <Card>
+ <CardContent className="flex flex-col items-center justify-center py-16 text-center">
+ <Plug className="mb-4 h-10 w-10 text-muted-foreground/50" />
+ <p className="text-lg font-medium text-muted-foreground">No MCP servers configured</p>
+ <p className="mt-1 text-sm text-muted-foreground/70">
+ Add one with <code className="font-mono">mercury mcp add</code>, then allow the tools you want.
+ </p>
+ </CardContent>
+ </Card>
+ )}
+
+ <div className="flex flex-col gap-4">
+ {servers.map((server) => (
+ <Card key={server.id}>
+ <CardHeader className="flex flex-row items-start justify-between gap-4 pb-3">
+ <div className="min-w-0 space-y-1">
+ <CardTitle className="text-base">{server.id}</CardTitle>
+ <p className="truncate text-xs text-muted-foreground">
+ {server.transport} · {server.target || "unknown target"}
+ </p>
+ </div>
+ <Badge variant="outline" className={cn("shrink-0 capitalize", STATE_STYLES[server.state])}>
+ {server.state}
+ </Badge>
+ </CardHeader>
+ <CardContent className="space-y-3">
+ {server.error && <p className="break-words text-sm text-destructive">{server.error}</p>}
+ {server.tools.length > 0 ? (
+ <ul className="divide-y divide-border rounded-md border text-sm">
+ {server.tools.map((tool) => {
+ const state = toolState(tool);
+ return (
+ <li key={tool.name} className="flex flex-wrap items-center justify-between gap-2 px-3 py-2">
+ <div className="min-w-0">
+ <span className="break-all font-mono text-xs">{tool.name}</span>
+ {tool.skipped && <p className="text-xs text-muted-foreground">{tool.skipped}</p>}
+ </div>
+ <span className={cn("text-xs font-medium", state.className)}>{state.label}</span>
+ </li>
+ );
+ })}
+ </ul>
+ ) : (
+ <p className="text-sm text-muted-foreground">
+ {server.state === "connected"
+ ? "This server reports no tools."
+ : "Tools appear once the server is connected."}
+ </p>
+ )}
+ </CardContent>
+ </Card>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/website/docs/cli-commands/commands.mdx b/website/docs/cli-commands/commands.mdx
index 37d71e79..a31796fd 100644
--- a/website/docs/cli-commands/commands.mdx
+++ b/website/docs/cli-commands/commands.mdx
@@ -15,6 +15,7 @@ title: Full Command Reference
| `mercury status` | Show config, providers, daemon PID, and budget |
| `mercury doctor` | Reconfigure settings — press Enter to keep current values |
| `mercury doctor --platform` | Show cross-platform terminal/daemon compatibility diagnostics |
+| `mercury doctor --mcp` | Connect to every enabled MCP server and report its status |
| `mercury setup` | Re-run the setup wizard (same as doctor) |
| `mercury help` | Show the full manual (tools, commands, config paths) |
| `mercury service install` | Install as system service (auto-start on boot) |
@@ -41,3 +42,21 @@ The `mercury skills` command tree talks to [skills.mercuryagent.sh](https://skil
| `mercury skills doctor` | Check install root, registry connectivity, cache |
Shared flags: `--json`, `--registry <url>`, `-q`, `-y`. Environment overrides: `MERCURY_SKILLS_REGISTRY`, `MERCURY_SKILLS_INSTALL_ROOT`.
+
+## MCP servers
+
+The `mercury mcp` commands manage the [MCP servers](../integrations/mcp) whose tools Mercury can use. Changes are saved to `~/.mercury/mercury.yaml` and the background daemon is restarted to apply them.
+
+| Command | Description |
+|---------|-------------|
+| `mercury mcp list` | Show configured servers, tool filters and env/header settings (secrets masked) |
+| `mercury mcp add <id> --stdio <command> [-- args...]` | Add a local server; shows the command and asks before saving |
+| `mercury mcp add <id> --http <url>` | Add a remote Streamable HTTP server |
+| `mercury mcp test <id>` | Connect once and list every tool as allowed, hidden or skipped |
+| `mercury mcp allow <id> <tools...>` | Show these tools to the agent (`'*'` for all) |
+| `mercury mcp disallow <id> <tools...>` | Hide these tools again |
+| `mercury mcp enable <id>` | Enable a server (asks before starting a stdio command) |
+| `mercury mcp disable <id>` | Disable a server without removing it |
+| `mercury mcp remove <id>` | Remove a server |
+
+`add` options: `--env KEY=VALUE`, `--header 'Name: value'`, `--cwd <dir>`, `--allow <tools>`, `--auto-approve <tools>`, `--allow-private`, `--disabled`, `-y`. Use `${env:NAME}` (in single quotes) for secrets kept in `~/.mercury/.env`.
diff --git a/website/docs/cli-commands/doctor.mdx b/website/docs/cli-commands/doctor.mdx
index 7144bc4a..6316e79e 100644
--- a/website/docs/cli-commands/doctor.mdx
+++ b/website/docs/cli-commands/doctor.mdx
@@ -31,3 +31,13 @@ This prints:
- Daemon status
- Spotify inline-art support status
- Keybinding fallbacks (`/view`, `/ws exit`, etc.)
+
+## MCP Servers
+
+Use `--mcp` to connect to every enabled [MCP server](../integrations/mcp) and report its health:
+
+```bash
+mercury doctor --mcp
+```
+
+Each server is listed as connected (with its tool count and how many tools are allowed), failed (with the reason and the end of the server's stderr), or disabled. Configuration problems, literal secrets in `mercury.yaml`, and tools skipped because their schema can't be used are listed too. The command exits with status 1 if any server fails, so it can be used in scripts.
diff --git a/website/docs/cli-commands/in-chat-commands.mdx b/website/docs/cli-commands/in-chat-commands.mdx
index 01bf3b78..b406bd63 100644
--- a/website/docs/cli-commands/in-chat-commands.mdx
+++ b/website/docs/cli-commands/in-chat-commands.mdx
@@ -17,6 +17,8 @@ Type these during a conversation with Mercury. Most work in both CLI and Telegra
| `/models` | List configured models/providers for this session |
| `/models use <provider>` | Switch the current session model/provider |
| `/tools` | List all currently loaded tools |
+| `/mcp` | Show [MCP servers](../integrations/mcp) and whether they are connected |
+| `/mcp tools <server>` | List an MCP server's tools and which ones the agent may use |
| `/skills` | List installed skills · see [dedicated page](./skills) for the full surface |
| `/skills search <query>` | Search the registry at [skills.mercuryagent.sh](https://skills.mercuryagent.sh) |
| `/skills view <id>` | Show title, version, description, and registry URL for `<category>/<slug>` |
diff --git a/website/docs/integrations/mcp.mdx b/website/docs/integrations/mcp.mdx
new file mode 100644
index 00000000..efe0e504
--- /dev/null
+++ b/website/docs/integrations/mcp.mdx
@@ -0,0 +1,215 @@
+---
+id: mcp
+title: MCP Servers
+---
+
+Mercury is a [Model Context Protocol](https://modelcontextprotocol.io/) (MCP) client. Connect it to MCP servers — local programs or remote endpoints — and their tools become available to the agent next to Mercury's built-in tools: your issue tracker, a database, internal company tools, a browser, anything that ships as an MCP server.
+
+You stay in control. A server's tools are hidden until you allow them, every call asks you first in **Ask Me** mode, and **Allow All does not cover MCP tools** — only tools you name in `autoApprove` run without a prompt.
+
+:::info[What is supported]
+
+MCP **tools** over **stdio** (a local command Mercury starts) and **Streamable HTTP** (a remote URL), with static headers for authentication. MCP resources, prompts, sampling, OAuth sign-in and legacy SSE servers are not supported yet. Mercury Bots do not get MCP tools.
+
+:::
+
+## Quick start
+
+### 1. Keep secrets in `.env`
+
+Put tokens in `~/.mercury/.env`, never in `mercury.yaml`:
+
+```bash
+# ~/.mercury/.env
+DOCS_MCP_TOKEN=your-token-here
+```
+
+Configuration refers to them as `${env:DOCS_MCP_TOKEN}`. Mercury resolves the reference only when it connects, so the value is never written back into `mercury.yaml`.
+
+### 2. Add a server
+
+A local **stdio** server — Mercury shows you the exact command and asks before saving:
+
+```bash
+mercury mcp add files --stdio npx -- -y @modelcontextprotocol/server-filesystem ~/Documents
+```
+
+A remote **HTTP** server with a bearer token:
+
+```bash
+mercury mcp add docs --http https://mcp.example.com/mcp --header 'Authorization: Bearer ${env:DOCS_MCP_TOKEN}'
+```
+
+Use single quotes around `${env:…}` so your shell doesn't expand it. `add` connects once to test the server and lists its tools before saving.
+
+### 3. Allow the tools you want
+
+Nothing is enabled until you say so:
+
+```bash
+mercury mcp test files # see every tool the server offers
+mercury mcp allow files list_directory search_files
+```
+
+Allowed tools appear to the agent as `mcp__files__list_directory`, `mcp__files__search_files`, and so on. If the daemon is running, Mercury restarts it to apply the change.
+
+### 4. Use them
+
+Ask Mercury something that needs the tool. In Ask Me mode you'll see:
+
+```
+MCP tool call
+Server: files
+Tool: list_directory
+Arguments:
+{
+ "path": "/Users/you/Documents"
+}
+```
+
+Answer **Yes** (this call), **Always** (this tool, in this chat, until Mercury restarts) or **No**.
+
+## Commands
+
+| Command | Description |
+|---------|-------------|
+| `mercury mcp list` | Configured servers, their tool filters, and env/header settings (secrets masked) |
+| `mercury mcp add <id> --stdio <command> [-- args...]` | Add a local server |
+| `mercury mcp add <id> --http <url>` | Add a remote Streamable HTTP server |
+| `mercury mcp test <id>` | Connect once and list every tool as allowed, hidden or skipped |
+| `mercury mcp allow <id> <tools...>` | Show these tools to the agent (`'*'` for all) |
+| `mercury mcp disallow <id> <tools...>` | Hide these tools again |
+| `mercury mcp enable <id>` / `disable <id>` | Turn a server on or off without removing it |
+| `mercury mcp remove <id>` | Remove a server |
+| `mercury doctor --mcp` | Connect to every enabled server and report its health |
+
+Options for `add`:
+
+| Option | Applies to | Meaning |
+|--------|-----------|---------|
+| `--env KEY=VALUE` | stdio | Environment variable for the server process (repeatable). Use `${env:NAME}` for secrets. |
+| `--cwd <dir>` | stdio | Working directory for the server process |
+| `--header 'Name: value'` | http | HTTP header (repeatable). Use `${env:NAME}` for secrets. |
+| `--allow-private` | http | Allow a private or loopback address (see [Security](#security)) |
+| `--allow a,b` | both | Tools to show to the agent (`'*'` for all) |
+| `--auto-approve a,b` | both | Tools that run without asking — also in scheduled runs |
+| `--disabled` | both | Save without enabling |
+| `-y, --yes` | both | Skip confirmations |
+
+In any chat, `/mcp` shows each server's status and `/mcp tools <server>` lists its tools. These are read-only: servers can only be added or enabled from the terminal. The web dashboard has a read-only **MCP** page with the same information.
+
+## Configuration reference
+
+Servers live under `mcp.servers` in `~/.mercury/mercury.yaml`. The `mercury mcp` commands edit this for you; you can also edit it by hand and restart Mercury.
+
+```yaml
+mcp:
+ servers:
+ files:
+ transport: stdio
+ command: npx
+ args: ["-y", "@modelcontextprotocol/server-filesystem", "/Users/you/Documents"]
+ tools:
+ allow: [list_directory, search_files]
+ docs:
+ transport: http
+ url: https://mcp.example.com/mcp
+ headers:
+ Authorization: "Bearer ${env:DOCS_MCP_TOKEN}"
+ tools:
+ allow: ["*"]
+ deny: [delete_page]
+ autoApprove: [search]
+ enabled: true
+```
+
+| Field | Transport | Description |
+|-------|-----------|-------------|
+| server id (the key) | both | Lowercase letters, digits and `-`, starting with a letter, up to 24 characters |
+| `transport` | both | `stdio` or `http` |
+| `command`, `args` | stdio | The program to start and its arguments. `${env:NAME}` works in `args`. |
+| `env` | stdio | Extra environment variables for the server process. `${env:NAME}` works here. |
+| `cwd` | stdio | Working directory |
+| `url` | http | The server's Streamable HTTP endpoint (`http` or `https`) |
+| `headers` | http | Static request headers. `${env:NAME}` works here. |
+| `allowPrivate` | http | `true` to allow private, loopback and `.local`/`.internal` addresses |
+| `enabled` | both | `false` to keep the server configured but not connected |
+| `timeoutMs` | both | Per-call timeout (default 60000) |
+| `tools.allow` | both | Tool names the agent may see; `"*"` means all. **Default: none.** |
+| `tools.deny` | both | Tool names that are always hidden; wins over `allow` |
+| `tools.autoApprove` | both | Exact tool names that run without asking (no wildcards) |
+
+An invalid server entry is skipped with a warning in the log and in `mercury doctor --mcp`; the rest still load. A missing `${env:NAME}` variable marks that server as failed with `env NAME is not set`.
+
+## How Mercury runs servers
+
+- **When.** Enabled servers connect in the background when Mercury starts. A slow or broken server never delays startup or blocks other tools. Servers reconnect with backoff (1s doubling to 5 minutes, up to 10 attempts) if a connection drops.
+- **Where.** The process that runs the agent owns the connections — normally the background daemon. The attach terminal, and `mercury code` while the daemon runs, do not start servers themselves.
+- **Tool changes.** If a server announces that its tool list changed (`tools/list_changed`), Mercury refreshes it. New tools are hidden unless your `allow` list covers them, and run without asking only if their exact name is in `autoApprove`.
+- **Tool names.** Tools are exposed as `mcp__<server>__<tool>`. Characters outside `A-Z a-z 0-9 _ -` become `_`, and names are capped at 64 characters (some model providers reject longer names); a shortened or clashing name gets a short hash suffix. `mercury mcp test` shows the exact names.
+- **Unusable tools.** A tool whose input schema can't be passed to the model (not an object, larger than 16 KB, or referencing a remote `$ref`) is skipped and reported with the reason. Descriptions inside a schema are shortened to 300 characters, since the model reads them on every turn.
+- **Results.** Text is passed to the model, capped at 32 KB per call. Images and audio are replaced by a short placeholder such as `[image/png, 12.3 KB — not shown]`. An error result from the server reaches the agent as `Error: …`.
+
+## Permissions
+
+MCP tools have their own rules, separate from the shell and file tools:
+
+| Situation | What happens |
+|-----------|--------------|
+| Tool not in `allow` (or in `deny`) | The agent can't see it |
+| Ask Me mode | You're asked before every call, with server, tool and arguments (shown whole up to 4,000 characters; longer ones show the start and the end) |
+| You answer **Always** | That tool runs without asking in that chat until Mercury restarts |
+| **Allow All** mode | You're **still asked** — Allow All never covers MCP tools |
+| Tool in `autoApprove` | Runs without asking, in chats and in unattended runs |
+| Scheduled tasks and sub-agents | They ask on the chat they came from, like a normal call; nothing is approved for them. A run with no one to ask (fail-closed, internal) only runs `autoApprove` tools |
+| Plan mode | MCP tools are not available |
+| Telegram/Signal members (non-admins) | MCP tools are not available |
+| Mercury Bots | MCP tools are not available |
+
+`autoApprove` takes exact tool names only, so a tool a server adds later can never slip in through a wildcard. Hints that a server sends about its own tools (such as "read-only") never change these rules.
+
+## Security
+
+MCP servers are third-party code and third-party text. Mercury treats them that way:
+
+- **Untrusted text.** Tool descriptions and results come from the server and can contain prompt-injection attempts ("ignore your instructions and…"). They reach the model like any web page would, and they can never change permissions. Only allow tools from servers you trust, and prefer Ask Me for anything that writes or sends.
+- **Process isolation.** A stdio server does **not** inherit Mercury's environment, so your model provider API keys and other `.env` values never reach it. It gets only a minimal set of variables (`HOME`, `LOGNAME`, `PATH`, `SHELL`, `TERM`, `USER` on macOS/Linux; `APPDATA`, `COMSPEC`, `HOMEDRIVE`, `HOMEPATH`, `LOCALAPPDATA`, `PATH`, `PATHEXT`, `PROCESSOR_ARCHITECTURE`, `PROGRAMDATA`, `PROGRAMFILES`, `PROGRAMFILES(X86)`, `PROGRAMW6432`, `SYSTEMDRIVE`, `SYSTEMROOT`, `TEMP`, `USERNAME`, `USERPROFILE`, `WINDIR` on Windows) plus the `env` you configure for it.
+- **Network.** HTTP servers go through Mercury's SSRF protection: private, loopback and `.local`/`.internal` addresses are refused unless you set `allowPrivate: true` for that server, and redirects to other origins are not followed. `allowPrivate` opens loopback and your LAN only: link-local addresses such as the cloud metadata service (`169.254.169.254`) stay blocked.
+- **Secrets.** Values you reference with `${env:NAME}` are resolved at connect time and masked as `****` wherever they could surface — logs, tool results, server stderr, `mercury mcp list`, `/mcp`, `mercury doctor --mcp`, the dashboard and `/api/mcp`. A literal token typed into `mercury.yaml` triggers a warning, and so does handing a server one of Mercury's own keys (for example `${env:ANTHROPIC_API_KEY}`): that server would see it.
+- **Owner-only setup.** Adding or enabling a server is done from the terminal; the agent has no MCP tool for it. When the agent uses its file tools (`write_file`, `edit_file`, `create_file`, `delete_file`) on `mercury.yaml`, `permissions.yaml` or `.env`, Mercury always asks first — even under Allow All — and refuses in unattended runs. Shell commands that change MCP setup (`mercury mcp add`, `enable`, `allow`… or anything that names `mercury.yaml`) also always ask, even under Allow All, and are refused in unattended runs. Other shell edits to `permissions.yaml` or `.env` follow your permission mode.
+
+## Checking health
+
+```bash
+mercury mcp test <id> # one server, with its tool list and stderr on failure
+mercury doctor --mcp # every enabled server; exits 1 if any fails
+```
+
+```
+ MCP servers
+ ✓ files: connected, 14 tools, 2 allowed — npx
+ ✗ docs: failed — env DOCS_MCP_TOKEN is not set — https://mcp.example.com
+ - old: disabled — uvx
+```
+
+In chat, `/mcp` shows the live status of the running Mercury; the dashboard's **MCP** page shows the same.
+
+## Troubleshooting
+
+| Symptom | Fix |
+|---------|-----|
+| `env NAME is not set` | Add `NAME=…` to `~/.mercury/.env` and restart Mercury |
+| `Blocked: … is a private/internal address` | The server is on your machine or network. Set `allowPrivate: true` (or add it with `--allow-private`) if you trust it |
+| `Connection closed` right after start | The command failed. `mercury mcp test <id>` prints the server's stderr — often a missing package, a wrong path, or a missing token |
+| `connect timed out after 15000 ms` | The server didn't answer the MCP handshake. Check it speaks MCP over stdio (not HTTP), or that the URL is the MCP endpoint |
+| `HTTP 401` / `403` | Check the token in `.env` and the header name the server expects |
+| Tool missing for the agent | It isn't in `tools.allow` — `mercury mcp test <id>` shows hidden and skipped tools |
+| `skipped: input schema …` | The server's schema for that tool can't be sent to the model; nothing to configure |
+| `MCP tool … needs approval` in a scheduled task | Add the tool to `tools.autoApprove` if it should run unattended |
+| Command works in your shell but not in the daemon | The background service runs with a fixed `PATH`. Use the full path to the program (for example `/opt/homebrew/bin/uvx`) |
+
+## Platform notes
+
+- **Windows.** Commands such as `npx` that are `.cmd` shims work as `command: npx`.
+- **Standalone binaries.** MCP is built into the standalone binaries (verified on the Windows binary; macOS and Linux run the same bundled code). Stdio servers still need their own runtime installed — Node.js for `npx`, Python for `uvx`.
+- **Termux.** MCP is untested on Termux. Install Mercury with npm there; stdio servers that only need Node.js are expected to work.
diff --git a/website/sidebars.ts b/website/sidebars.ts
index 2a04ac86..29607cb2 100644
--- a/website/sidebars.ts
+++ b/website/sidebars.ts
@@ -56,6 +56,7 @@ const sidebars: SidebarsConfig = {
'integrations/whatsapp',
'integrations/optimus',
'integrations/spotify',
+ 'integrations/mcp',
'integrations/coding-workspace',
'integrations/sub-agents',
],