> ## Documentation Index
> Fetch the complete documentation index at: https://docs.myrmagent.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# MCP Integration

> Connect external tools and services using the Model Context Protocol.

# MCP Integration

Myrm supports the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) for connecting external tools and services to your agents.

## What is MCP?

MCP is an open standard that lets AI agents connect to external data sources and tools through a unified protocol. Instead of building custom integrations, you can connect any MCP-compatible server.

## Service Catalog (One-Click Connect)

The fastest way to connect popular services. Navigate to **Settings > Integrations > Service Catalog** to browse 29 prebuilt integrations across 9 categories:

| Category          | Services                                                                      |
| ----------------- | ----------------------------------------------------------------------------- |
| **API Tools**     | Postman                                                                       |
| **Browser**       | Playwright, Browserbase                                                       |
| **Communication** | Gmail, Slack, Feishu, DingTalk                                                |
| **Data Storage**  | PostgreSQL, Local File System, Google Drive, Supabase                         |
| **Design**        | Figma (descriptive output for better code generation)                         |
| **Dev Tools**     | GitHub, GitLab, Gitee, Gitee Enterprise, Sentry, Code Review Graph, CodeGraph |
| **Docs**          | Context7, Microsoft Learn, AWS Documentation                                  |
| **Productivity**  | Notion, Todoist, Google Calendar, Linear                                      |
| **Web Search**    | Firecrawl (Keyless free tier), Exa, Brave Search                              |

Each entry includes:

* **Pre-configured connection details** (command, args, URL)
* **Guided credential input** with help links to the provider's token page
* **Keyless zero-config support** for select services (e.g., Firecrawl free tier -- no API key needed)
* **Security scan** before connecting (SSRF + malicious package detection)
* **Bilingual descriptions** (English and Chinese)

Click **Connect** on any service card. For keyless services like Firecrawl, just click Connect with no credentials needed. For other services, fill in the required API key and you're ready.

## Cloud Storage & File Export

Myrm provides 6 paths to sync and export files to any cloud storage service — no dedicated connector required for each provider:

| Path                             | Coverage                                             | Example                                              |
| -------------------------------- | ---------------------------------------------------- | ---------------------------------------------------- |
| **Built-in MCP**                 | Google Drive, Notion (one-click connect via Catalog) | "Save this to my Google Drive"                       |
| **Code Execution Sandbox**       | Any cloud SDK (boto3, dropbox, onedrive-sdk)         | "Upload report.pdf to my S3 bucket"                  |
| **Browser Automation**           | Web-based storage with no API (Baidu Netdisk, etc.)  | "Save this to my Baidu Netdisk"                      |
| **MCP Marketplace**              | Community MCP servers for Dropbox, OneDrive, etc.    | Install from Registry with one click                 |
| **Bi-directional File Transfer** | Agent files auto-pushed via IM channels              | Files appear as attachments in Feishu/Slack/Telegram |
| **Artifact Share Links**         | HMAC-secured public share URLs                       | Share generated reports with external stakeholders   |

:::tip
Unlike competitors that lock you into a single cloud ecosystem, Myrm's open architecture lets you connect to **any** storage service through multiple paths. The Agent automatically chooses the best approach based on your request.
:::

## Integration Memory (Workspace Sync)

Any connected MCP server can be automatically used as a knowledge source. Navigate to **Settings > Integrations > Integration Memory** to sync external data into your AI's long-term memory.

### How It Works

1. **Connect** a service via the Service Catalog (e.g., Notion, GitHub, Gmail)
2. Click **Sync All** in the Integration Memory section
3. The system automatically:
   * Detects the best fetch tool from the MCP server's catalog
   * Pulls data using incremental sync (detects `since`/`after` parameters)
   * Deduplicates by `provider::external_id` (idempotent re-sync safe)
   * Embeds content into the vector store
   * Builds a tree structure in the knowledge graph
   * Extracts high-value profile traits via MemoryExtractor

### Key Features

| Feature                    | Description                                                                |
| -------------------------- | -------------------------------------------------------------------------- |
| **Universal bridging**     | MCPBridgeProvider auto-bridges any MCP server — no per-service code needed |
| **Concurrent sync**        | Up to 5 providers synced in parallel                                       |
| **Smart parsing**          | Handles list, dict, and raw string responses from MCP tools                |
| **Tree management**        | Hierarchical structure with summaries for browsing and removal             |
| **Auto knowledge seeding** | Freshly synced data is processed by MemoryExtractor for key insights       |
| **Per-provider sync**      | Sync individual providers or all at once                                   |

### Managing Synced Data

* **Status overview**: See total providers, indexed items, and tree count
* **Per-tree controls**: Sync or remove individual data trees
* **Sync results**: View created/updated/skipped/failed counts per provider

## Adding Custom MCP Servers

### From the GUI

1. Navigate to **Settings > Tools > MCP**
2. Click **Add Server**
3. Enter the server configuration:
   * **Name**: Display name for the server
   * **Command**: The command to start the server (e.g., `npx @mcp/server-github`)
   * **Arguments**: Command-line arguments
   * **Environment Variables**: Required environment variables (e.g., API keys)
4. Save — the server starts automatically and its tools become available to agents

### From Configuration File

Add MCP servers to `mcp_servers.json`:

```json theme={null}
{
  "servers": [
    {
      "name": "github",
      "command": "npx",
      "args": ["@mcp/server-github"],
      "env": {
        "GITHUB_TOKEN": "ghp_..."
      }
    }
  ]
}
```

## Building Custom MCP Servers (AI-Guided)

Don't want to write an MCP server from scratch? Activate the **mcp-builder** skill and ask the agent to build one for you.

### How to Use

1. Go to **Settings > Agent > Skills** and enable the `mcp-builder` skill
2. Start a conversation and describe what you need: *"Build an MCP server that connects to Jira for project management"*
3. The agent follows a structured 4-phase workflow:

| Phase              | What Happens                                                                          |
| ------------------ | ------------------------------------------------------------------------------------- |
| **Research**       | Investigates the target API (auth, endpoints, rate limits)                            |
| **Implementation** | Writes the server in Python (FastMCP) or TypeScript (MCP SDK) with proper annotations |
| **Verify**         | Runs a verification script to confirm the server starts and passes security scanning  |
| **Register**       | Generates the configuration for Settings > MCP and tests the tools in conversation    |

### Built-in Quality Guarantees

* **Security annotations** — Read-only operations get `readOnlyHint: true` (auto-approve), destructive operations get `destructiveHint: true` (warning badge)
* **Error handling** — All HTTP calls have timeouts, retries, and actionable error messages
* **Pagination** — Large result sets are paginated to prevent token explosion
* **Environment variables** — Secrets are never hardcoded

## Schema Handling

Myrm automatically optimizes MCP tool schemas for LLM compatibility:

| Feature                         | Description                                                                                                                                                                                                                                                  |
| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| **Schema Flattening**           | Deeply nested schemas (depth > 2 or leaves > 10) are automatically flattened                                                                                                                                                                                 |
| **Type Intelligent Fix**        | 7 auto-fixes: nullable completion, mixed-union container parsing, enum/const null recognition, reverse coercion (dict→string), boolean/number string conversion, markdown code block stripping, deep-nested dot-path flattening                              |
| **Dot-Path Detection**          | Automatically detects if the model uses dot notation for nested params                                                                                                                                                                                       |
| **\$ref Resolution**            | Full recursive JSON Schema `$ref` resolution                                                                                                                                                                                                                 |
| **Circular Reference Guard**    | Max depth limit + visited tracking prevents infinite recursion                                                                                                                                                                                               |
| **Anthropic Schema Auto-Adapt** | Automatically strips unsupported JSON Schema keywords (`minimum`, `maximum`, `pattern`, `format`, `default`, `title`, etc.) for Claude models, folds constraint semantics into `description` to preserve LLM understanding. Zero manual configuration needed |
| **Description Safety Valve**    | Excessively long third-party descriptions auto-truncated to 2048 chars to prevent token waste                                                                                                                                                                |
| **Schema Cache Stability**      | Recursive key sorting + set field sorting eliminates serialization randomness from MCP server restarts, ensuring Prompt Cache hits                                                                                                                           |
| **Coercion Observability**      | Runtime counters track each fix type's trigger frequency, with DEBUG logging for diagnostics                                                                                                                                                                 |
| **Content Boundary Defense**    | All MCP return values pass through 5-layer `wrap_untrusted` defense chain to prevent Prompt Injection                                                                                                                                                        |

## Connection Management

### Persistent Sessions

Each MCP server runs on a single, persistent session that stays warm for the entire agent lifetime. Tool calls are serialized onto the session through an internal queue — no subprocess is spawned per call, and no re-initialization handshake is needed between calls.

### Execution Timeout Protection

Every MCP tool call is protected by a dual-layer timeout mechanism:

* **SDK layer** — `read_timeout_seconds` is passed to the MCP SDK session, preventing hung responses at the transport level
* **Wrapper layer** — An independent `asyncio.timeout` wraps the entire execution (including response normalization), catching tools that stall after transport confirms receipt
* **Per-server configurable** — Each server can set its own `connect_timeout` (default 15s) and `execute_timeout` (default 120s, max 300s)
* **Graceful degradation** — On timeout, a descriptive error string is returned to the LLM (not an exception), allowing the agent to decide next steps
* **Auto-retry on enumeration** — Tool discovery retries up to 3 times with 300ms backoff on transient failures

### Error Transparency

When an MCP tool reports a failure (`isError: true`), the full error chain is handled without losing information:

* **Server-side error pass-through** — The original error text from the MCP server is extracted and forwarded to the LLM exactly as reported
* **Security sanitization** — Credentials are redacted (`redact_sensitive_text`) and structural framing tokens are stripped (`sanitize`) to prevent prompt injection via error messages
* **Error classification** — Errors are categorized (network\_blocked, timeout, sandbox\_ro, etc.) enabling circuit-breaker patterns and targeted recovery
* **Circuit breaker** — Terminal errors (e.g. network permanently blocked) are registered; subsequent calls to the same category fail fast without retrying
* **Structured diagnostics** — Execution phase, tool name, output previews (head + tail truncation), and recovery hints are recorded for debugging
* **Frontend display** — Errors surface in the UI as structured progress steps with i18n messages, resolution steps, and recovery actions — not just raw text

### Self-Healing Reconnection

When a transport break occurs (subprocess crash, SSE/HTTP drop, idle timeout), the session actor reconnects in place:

* **Bounded backoff** — Up to 5 reconnect attempts with exponential backoff (0.5s to 8s cap)
* **Budget refresh** — A session that ran stable for 60+ seconds earns a fresh retry budget, so an unrelated blip hours later still gets full retries
* **In-flight call fails explicitly** — The call that hit the break is failed (no silent auto-retry of non-idempotent tools), but subsequent calls succeed on the fresh session
* **Proxy stability** — The tool objects held by the agent remain identical across reconnects, preserving prompt prefix cache hits

### Transport-Aware Keepalive

Remote transports (SSE, streamable HTTP) sit behind load balancers and NAT that silently drop idle TCP connections. The session actor sends a lightweight in-band ping (`list_tools`) every 180 seconds to keep the connection warm. Local stdio transports (pipes to subprocesses) never idle-disconnect and are left unprobed.

### Connection Pool

* **Singleton per server** — One warm connection per config-hash prevents resource leaks
* **Loop-aware** — Connections rebuild automatically on event-loop change
* **TTL recycling** — Long-idle connections are closed and recreated on demand
* **Last-resort rebuild** — The pool only rebuilds a connection when the actor's internal reconnect budget is fully exhausted

### CancelledError Protection

A guard prevents Python `CancelledError` from leaking through MCP channels, which could otherwise crash the MCP server process.

### Metrics

Connection metrics (success rate, latency, error rate) are tracked and available through the diagnostics API.

## Security

### SSRF Prevention

Myrm implements DNS pinning for MCP tool URLs:

* Resolved IPs are checked against private ranges (10.x, 172.16-31.x, 192.168.x)
* Localhost and link-local addresses are blocked by default
* URL validation prevents redirect-based SSRF attacks

### Malicious Package Detection

When MCP tools install dependencies, the OSV (Open Source Vulnerability) API is consulted in real-time to detect known malicious packages.

### Runtime Prompt Injection Protection

Every time MCP tools are registered (initial freeze) or dynamically refreshed (after `list_changed`), Myrm runs a runtime surface scan that inspects:

* **Server instructions** for embedded directives that could hijack agent behavior
* **Tool names** for deceptive names mimicking built-in tools
* **Tool descriptions** for injected prompt manipulation patterns

If suspicious content is detected, the server's tools are blocked with a `MCPRuntimePostureError` — the malicious tools never reach the agent's context. This prevents a class of attacks where a compromised or malicious MCP server subtly changes its tool descriptions to inject instructions into the agent's prompt.

### Tool Approval

MCP tools follow the same approval flow as built-in tools:

* Read-only tools execute automatically
* Write/destructive tools require user approval (unless in YOLO mode)
* Custom approval policies can be configured per MCP server

## Per-Tool Filtering

When configuring agents, you can control which tools from each MCP server are available — down to individual tool granularity.

### How to Use

1. Go to **Agent Config** (click the agent avatar in chat)
2. Under **MCP Servers**, each enabled server shows a **Tool Filter** toggle
3. Expand it to see all available tools with risk annotations
4. Toggle individual tools on/off using checkboxes

### Risk Annotations

Each tool is automatically classified by risk level:

| Risk Level  | Icon       | Description                                       |
| ----------- | ---------- | ------------------------------------------------- |
| **Safe**    | 🟢 Shield  | Read-only operations (`readOnlyHint: true`)       |
| **Caution** | 🟡 Eye     | Write operations (not read-only, not destructive) |
| **Danger**  | 🔴 Warning | Destructive operations (`destructiveHint: true`)  |

### Auto-Disable Dangerous Tools

When you first enable an MCP server on an agent, tools marked as **destructive** are automatically excluded from the selection. You can manually re-enable them if needed.

### Filter Summary

The tool filter header shows a count badge (e.g., `5/20`) indicating how many tools are active out of the total available.

## Multimodal Tool Results

MCP tools can return rich content beyond plain text — screenshots, images, and structured data are all handled natively.

### Image Content

When an MCP server returns `ImageContent` (e.g., Playwright screenshots, diagram generators), Myrm renders the image directly in the chat:

* Base64 image data flows through the streaming pipeline and renders in the **Tool Image Gallery**
* Multiple images per tool result are supported (grid layout with lightbox preview)
* For models that don't support vision, images are automatically stripped by the media filter — no configuration needed

### Structured Content

When an MCP server returns `structuredContent` (JSON metadata alongside text), Myrm extracts and includes it as supplementary context for the LLM, enabling more precise structured reasoning.

### Tool Filtering

You can control which tools are exposed per MCP server, **per agent**:

* **Include list** — Only specified tools are registered (whitelist)
* **Exclude list** — Specified tools are hidden (blacklist)
* **Per-agent granularity** — Different agents can enable different tools from the same MCP server (e.g., a "Code Reviewer" agent sees only read-only GitHub tools, while a "DevOps" agent sees all)
* Configure via the GUI in the **Agent Config Panel > MCP > Tool Selection**

### Safety Annotations

MCP tools carry [annotation hints](https://spec.modelcontextprotocol.io/specification/2025-03-26/server/tools/#annotations) that Myrm uses for automatic risk management:

| Annotation        | Effect                                                                                                                             |
| ----------------- | ---------------------------------------------------------------------------------------------------------------------------------- |
| `readOnlyHint`    | Tool marked as read-only; eligible for auto-approval when `readOnly && !openWorld && !destructive` (both PTC and direct MCP paths) |
| `destructiveHint` | Tool marked as dangerous; **disabled by default** in the smart safe set and highlighted with a warning badge in the GUI            |
| `idempotentHint`  | Tool marked as safe to retry                                                                                                       |
| `openWorldHint`   | Tool may interact with external systems beyond the MCP server                                                                      |

### Default Safe Set

When you first enable an MCP server for an agent, Myrm inspects tool annotations and automatically builds a **safe default selection**:

* All `readOnlyHint` tools are enabled
* Tools with `destructiveHint` are disabled and flagged with a warning banner ("N destructive tools disabled by default")
* You can always override the defaults in the Tool Selection GUI

### Tool Name Isolation

When multiple MCP servers are enabled, tool names can collide (e.g. both a GitHub and GitLab server may expose `search_repos`). Myrm applies **server-prefix isolation** to every MCP tool:

```
mcp__{server}__{tool}
```

* **Double-underscore delimiters** — Unlike single-underscore schemes (which are ambiguous when server names contain underscores), the `__` delimiter allows unambiguous parsing back to `(server, tool)` pairs
* **Permission safety** — Prefixed names never collide with built-in tool names, preventing accidental permission bypass
* **Audit traceability** — Every tool invocation log entry clearly shows which MCP server the tool belongs to
* **Transparent to users** — The GUI always displays the friendly original tool name; prefixing is internal to the engine

## Dynamic Tool Discovery

When an MCP server adds, removes, or updates its tools at runtime, Myrm detects the change automatically via the standard `notifications/tools/list_changed` notification:

* **Zero-downtime refresh** — The session actor re-fetches the tool list and updates the execution layer without interrupting in-flight calls (serialized through the internal queue, no locks)
* **Prompt cache stability** — The prompt-facing proxy tools remain frozen; only the internal execution map is updated, so prompt prefix cache hits are never compromised
* **Timeout protection** — The refresh re-fetch is bounded by the same connect timeout as session initialization, so a hung MCP server cannot deadlock the owner task
* **Change logging** — Added and removed tools are logged at WARNING level for visibility; no-op refreshes are logged at INFO level
* **Transparent to agents** — Agents continue using their existing tool references; new tools become callable immediately, removed tools fail explicitly on next invocation

This is especially useful for MCP servers that dynamically register tools based on user state (e.g., a project management server that adds tools when a new board is created).

## Deferred Loading

To prevent tool schema bloat in the system prompt, MCP tools support **deferred loading**:

* Tools are registered but not included in the initial prompt
* When the agent needs a specific capability, the tool is loaded on demand
* This keeps the system prompt compact and cache-friendly

## Reverse MCP Server (Connect)

Myrm can also act as an **MCP server**, exposing its memory system to external AI agents (Claude Code, Cursor, Codex, Windsurf, Gemini CLI). This means your knowledge persists across all your AI tools.

### How It Works

Navigate to **Settings > Memory > Connect** to launch the Connect Wizard:

1. **Choose your Myrm Agent** — Select which Agent Profile the external tool should bind to. The external tool will read/write that agent's memory space, including any shared contexts bound to it.
2. **Choose your IDE** — Select from 5 supported MCP clients
3. **Generate config** — One click generates a Bearer token (carrying the agent scope) and a ready-to-paste config snippet
4. **Paste into your IDE** — Copy the snippet into your IDE's MCP settings file
5. **Done** — Your external agent now has scoped access to the selected Myrm Agent's memory

Each token is scoped to a specific Agent Profile. When the external tool makes MCP requests, Myrm's middleware automatically resolves the token to the correct agent and binds the appropriate memory namespace + shared contexts. This means different external tools can connect to different Myrm agents with completely isolated memory spaces.

### Exposed Tools

| Tool                 | Description                                                                                                                                            |
| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `memory_search_tool` | Unified search across memory, wiki, and prior conversations via `corpus` parameter. Supports category filters and profile key lookup on memory corpus. |
| `memory_list`        | Enumerate and audit memories: overview mode for global stats and previews, category mode for paginated browsing of a single category                   |
| `memory_store`       | Store new knowledge, preferences, rules, events, or instructions                                                                                       |
| `memory_manage`      | Rate, update, correct, or delete existing memories                                                                                                     |

### Security

* **Bearer Token authentication** — Each connector gets a unique `myrm_mcp_*` token scoped to a specific Agent Profile
* **Per-agent memory isolation** — External tools only access the bound agent's memory and shared contexts, not other agents' data
* **One-click revoke** — Instantly invalidate a connector's access without affecting others
* **HTTP transport** — Works over the network (not limited to local stdio)
* **Doctor health check** — Verify connectivity from the GUI at any time

### Supported Clients

| Client      | Config Format | Config File Path                    |
| ----------- | ------------- | ----------------------------------- |
| Claude Code | JSON          | `~/.claude/claude_code_config.json` |
| Cursor      | JSON          | `.cursor/mcp.json`                  |
| Codex       | TOML          | `codex.toml`                        |
| Windsurf    | JSON          | `~/.windsurf/mcp_config.json`       |
| Gemini CLI  | JSON          | `~/.gemini/settings.json`           |

### Why This Matters

When you work in Cursor on code and then switch to Myrm's WebUI for research, both agents share the same memory. Project decisions stored by one agent are instantly available to the other — no manual context transfer needed.

## Enterprise Org MCP (Cloud SaaS)

On **cloud-hosted enterprise** deployments, IT admins can centrally manage MCP servers for the whole organization:

1. Navigate to **Settings → Enterprise → Org MCP** (owner/admin only)
2. Add HTTP/SSE MCP servers with name, URL, and optional auth headers
3. Changes are **pushed automatically** to every member sandbox via the control plane
4. If a sandbox is **sleeping**, delivery is queued and **replayed on wake** (up to 3 retries)
5. Employees see org-managed MCP servers as **read-only** under **Settings → MCP** — they cannot edit or remove IT-managed entries
6. **stdio MCP is blocked** in cloud sandboxes for security (local process servers are not allowed)

:::tip
This closes the gap competitors leave open: no org-wide MCP catalog, no automatic sync after idle sleep, and no IT/employee permission split. New hires get the same internal tools on day one without manual YAML or curl.
:::

## Troubleshooting

### Server Won't Start

1. Check the command path is correct and accessible
2. Verify required environment variables are set
3. Check server logs in **Settings > Tools > MCP > Logs**

### Tools Not Appearing

1. Wait 5-10 seconds after server start for tool discovery
2. Click **Refresh** in the MCP settings panel
3. Check if the server's tool list response is valid JSON Schema

### Connection Drops

The self-healing reconnect system handles most connection issues transparently — the session actor rebuilds the connection in place without user intervention. If a tool call fails due to a transport break, retry the message and the next call will land on the fresh session. For persistent failures after 5 reconnect attempts, check:

* Network connectivity to the MCP server
* Server process health (may need restart)
* Resource limits (file descriptors, memory)

### Local Editor MCP Probe Diagnostics

When you connect local-only integrations (for example Unreal Engine or Blender), Myrm runs `/api/v1/integrations/mcp/probe` **before** scan/verify. This avoids dead-end setup flows where users click Connect repeatedly without knowing the root cause.

| Category                  | Signal                                                                                | Meaning                                                                     | Next Action                                                               |
| ------------------------- | ------------------------------------------------------------------------------------- | --------------------------------------------------------------------------- | ------------------------------------------------------------------------- |
| Reachable                 | `reasonCode=reachable`                                                                | MCP endpoint responded in time                                              | Continue to scan/verify                                                   |
| Editor server not running | `reasonCode=connection_refused`                                                       | Port exists but nothing is listening                                        | Start the editor-side MCP server/plugin                                   |
| Local route unavailable   | `reasonCode=connection_unreachable`                                                   | Loopback path exists but local routing/VPN/proxy policy blocks reachability | Verify localhost routing, VPN/proxy policy, and editor MCP settings       |
| TLS trust failure         | `reasonCode=tls_verification_failed`                                                  | Certificate chain/hostname validation failed                                | Import enterprise CA or configure per-server CA bundle / mTLS             |
| Connection timeout        | `reasonCode=connection_timeout`                                                       | Target is reachable intermittently or too slow to respond                   | Check local network stability and editor MCP health, then retry           |
| Unexpected probe failure  | `reasonCode=probe_failed_unknown` + `recommendedMode=verify_local_network_and_editor` | A non-network runtime failure occurred while probing                        | Retry after checking editor MCP settings; use server logs for diagnostics |
| Loopback policy           | HTTP 400 + `localhost addresses only` detail                                          | Non-loopback endpoint was blocked by SSRF guard                             | Use `127.0.0.1` / `localhost` endpoint for local integrations             |

Additional behavior guarantees:

* If `shouldBlockConnect=true`, Myrm stops the connect chain immediately (no scan/verify fan-out), reducing noisy failures.
* The UI maps `reasonCode` to localized operator-facing messages, so infra and app teams can triage from the same signal.
* `recommendedMode` is actionable in one click: `start_local_editor_mcp` / `verify_local_network_and_editor` trigger a probe retry and auto-continue connect on success, while `local_or_tauri` opens local deployment guidance directly.
* Compared to competitors that surface generic network errors only, Myrm provides machine-readable diagnostics that can be automated in CI checks and onboarding scripts.

### Why this migration path is smoother than CLI-first flows

* **In-product remediation, not terminal handoff**: Operators can recover from local MCP failures inside the same Connect dialog. In contrast, OpenClaw's MCP page is explicitly an operator view and asks users to run terminal probe commands (`openclaw mcp doctor --probe`) for live proof.
* **Actionable contract instead of boolean pass/fail**: Myrm returns `reasonCode + recommendedMode + shouldBlockConnect`, so frontend behavior is deterministic (block fan-out, show localized cause, and provide one-click action). Hermes' `/api/mcp/servers/{name}/test` style response is primarily `ok/error/tools`, which is useful for diagnostics but less expressive for guided onboarding UX.
* **Noise reduction by design**: When the probe says block, Myrm stops scan/verify fan-out immediately. This prevents avoidable downstream failures and reduces "retry blindly" behavior during migration from legacy MCP setups.
* **Unknown-failure safety**: Unexpected probe failures return a sanitized operator message while server logs retain debuggable details, avoiding accidental leak of low-level exception internals to end users.

### OAuth Token Expiry

When an MCP server's OAuth token expires (common with GitHub, Linear, Notion, Slack integrations), Myrm detects the failure at runtime and guides you to re-authorize:

1. **Instant detection** — When a tool call receives an HTTP 401 from the MCP server, the error is caught immediately (no need to exhaust reconnect retries first)
2. **User notification** — A toast appears: **"{server} requires re-authorization"** with a one-click **"Reauthorize"** button
3. **One-click fix** — Click the button to jump directly to **Settings → Extensions** where you can re-authorize with OAuth
4. **Token hot-update** — After re-authorization, active sessions automatically pick up the fresh token via the connection pool — no page reload or session rebuild needed. The very next tool call uses the new credentials

## Enterprise Private MCP Tunnel (Cloud Only)

:::info Cloud deployment only
This feature is available exclusively for **cloud-hosted** Myrm deployments managed by the control plane. Local and Tauri users connect to MCP servers directly via stdio — no tunnel needed.
:::

For enterprise customers whose MCP servers run on private networks (behind firewalls, in VPCs, or on-premises), Myrm provides a **reverse tunnel** that lets your cloud-hosted AI agent securely access internal MCP servers — without exposing any ports or modifying firewall rules.

### How It Works

1. **Deploy tunnel-agent** — Install the open-source `myrm-tunnel-agent` on any machine inside your private network
2. **Register tunnel** — The agent registers with the control plane and receives a secure token
3. **Outbound-only connection** — The tunnel-agent initiates an outbound long-poll connection to the control plane relay — no inbound ports required
4. **Transparent relay** — When your cloud Myrm agent calls an internal MCP tool, the request is relayed through the tunnel to the internal MCP server and the response is returned transparently

### Security

| Feature                   | Description                                                                                                        |
| ------------------------- | ------------------------------------------------------------------------------------------------------------------ |
| **Zero inbound exposure** | Enterprise network only makes outbound connections — no firewall ports, no VPN, no public IP needed                |
| **mTLS encryption**       | End-to-end mutual TLS between tunnel-agent and control plane                                                       |
| **Token rotation**        | Authentication tokens can be rotated at any time without service interruption                                      |
| **Heartbeat monitoring**  | 60-second stale threshold with 30-second scan interval — offline tunnels are detected and marked within 90 seconds |
| **Instant revocation**    | IT administrators can revoke tunnel access immediately via the org admin panel                                     |

### Architecture

```
┌─ Enterprise Network ──────────┐     ┌─ Myrm Cloud ─────────────────┐
│                                │     │                               │
│  Internal MCP Server           │     │  CP Tunnel Relay (in-memory)  │
│       ↑                        │     │       ↑                       │
│  myrm-tunnel-agent ─── outbound ───→ │  org MCP → streamable_http    │
│  (open-source)         HTTPS   │     │       ↓                       │
│                                │     │  Cloud Agent (sandbox)        │
└────────────────────────────────┘     └───────────────────────────────┘
```

### Setting Up

1. **Register a tunnel** in the org admin panel (**Settings → Organization → MCP → Add Tunnel**)
2. Deploy `myrm-tunnel-agent` with the provided token and internal MCP server endpoint
3. The tunnel appears as an org-level MCP server — assign it to agents like any other MCP server

## Enterprise Managed Auth — IdP Group-Based MCP Access (Cloud Only)

:::info Cloud deployment only
This feature is available exclusively for **cloud-hosted** Myrm deployments with OIDC SSO configured. Local and Tauri users manage MCP access directly in their local settings.
:::

For enterprise customers using Identity Providers (Okta, Entra ID, Google Workspace, etc.), Myrm automatically maps **IdP group memberships** to **org MCP server access** — so IT administrators can control which teams see which tools, with zero manual per-user configuration.

### How It Works

1. **OIDC groups claim** — When a user logs in via SSO, Myrm extracts the `groups` claim from the OIDC response and stores it on the user's org membership record
2. **Per-MCP group whitelist** — Org admins configure an optional `acl_groups` list on each org MCP server (empty = visible to all members)
3. **Automatic filtering** — When MCP configurations are pushed to a user's sandbox, only servers where the user's IdP groups intersect with the server's ACL groups are included
4. **Login refresh** — Group memberships are automatically refreshed on every OIDC login — no manual sync needed

### Configuring Group-Based Access

1. Navigate to **Settings → Organization → MCP Servers**
2. When creating or editing an MCP server, enter IdP group names in the **Access Groups** field (comma-separated)
3. Leave the field empty to make the server visible to all organization members
4. Members whose IdP groups match at least one configured group will see and use the server

### Offboarding

When an employee is offboarded via the org admin panel, Myrm immediately pushes an empty MCP server list to their sandbox — revoking all org MCP access instantly. No manual cleanup required.

### Security

| Feature                        | Description                                                                                          |
| ------------------------------ | ---------------------------------------------------------------------------------------------------- |
| **Zero-touch provisioning**    | New employees see the right MCP tools automatically based on their IdP groups — no IT tickets needed |
| **Least-privilege by default** | Servers with ACL groups are invisible to non-matching members                                        |
| **Instant revocation**         | Offboarding cuts MCP access immediately                                                              |
| **Audit-friendly**             | Group memberships are visible in the org members API for compliance review                           |
