> For the complete documentation index, see [llms.txt](https://docs.visdom.virtuslab.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.visdom.virtuslab.com/visdom-ai-gateway/mcp-gateway/guardrails-and-emergency-stop.md).

# Guardrails, limits and emergency stop

What the MCP gateway checks on every tool call: secrets and bank rules in arguments, personal data in results, rate limits, an optional OPA policy, and the switches up to an emergency stop.

Every tool call through the MCP gateway passes three plugins before the tool server sees it, and one after. They run inside the MCP gateway, on every virtual server and every tool:

| Order | Plugin         | When                                    | What it does                                                                                            | Default |
| ----- | -------------- | --------------------------------------- | ------------------------------------------------------------------------------------------------------- | ------- |
| 1     | `opa-policy`   | Before each tool call and resource read | Asks your OPA server; the call goes on only if the policy allows it.                                    | Off     |
| 2     | `rate-limit`   | Before each tool call and prompt fetch  | Counts calls per token owner and per tool.                                                              | On      |
| 3     | `visdom-guard` | Before each tool call                   | Refuses denied tools, secrets, the bank's refusing rules and denied argument patterns in the arguments. | On      |
| 3     | `visdom-guard` | After each tool call                    | Masks personal data and the bank's masking rules in the result.                                         | On      |

The plugin configuration is `deploy/compose/contextforge/plugins/config.yaml` in Compose. The Helm chart uses the same file unless you set `mcpGateway.plugins.config` (the whole configuration, as YAML). Each plugin has a `mode`: `enforce`, `permissive` (log only) or `disabled`.

## Refused and masked: visdom-guard

`visdom-guard` uses the same detectors and the same bank rules as the LLM gateway's guardrails (`deploy/guardrails/detectors.py`, `deploy/guardrails/rules.json`).

**Before the call**, the arguments are checked in this order; the first match refuses the call, and the tool server is never called:

| Check                                                                                                                                                                     | Code                                                          |
| ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------- |
| The tool is on the plugin's deny-list (`denied_tools`)                                                                                                                    | `VISDOM_TOOL_DENIED`                                          |
| A secret in any argument: private key, AWS access key, GitHub, Slack, Google, Anthropic or OpenAI key, Azure storage key, JSON Web Token, password in a connection string | `VISDOM_SECRET` (the message names the kind, never the value) |
| One of the bank's refusing rules that applies to the MCP gateway                                                                                                          | `VISDOM_BANK_RULE` (the message names the rule)               |
| A regular expression in `denied_argument_patterns`                                                                                                                        | `VISDOM_ARGUMENT_DENIED`                                      |

**After the call**, personal data in the result is masked before it reaches the client and its model: PESEL, NIP and IBAN (checked by checksum), card numbers (Luhn), e-mail addresses and phone numbers become `<PESEL>`, `<NIP>`, `<IBAN>`, `<PL_IBAN>`, `<CARD_NUMBER>`, `<EMAIL>`, `<PHONE>`. Matches of the bank's masking rules become `<RULE:name>`. The call is not refused: the client gets the masked result. Tools listed in `unmasked_tools` keep their results as they are, for an approved use case that needs the data.

{% hint style="info" %}
Names and addresses (Microsoft Presidio) are detected in the LLM gateway only. In tool results the MCP gateway masks the identifiers above and the bank's own rules.
{% endhint %}

```yaml
  - name: visdom-guard
    kind: visdom_guard.plugin.VisdomGuard
    hooks: ["tool_pre_invoke", "tool_post_invoke"]
    mode: enforce          # enforce | permissive (log only) | disabled
    priority: 50
    conditions: []         # every server and tool; narrow with server_ids / tools
    config:
      denied_tools: []                  # tool names refused outright, e.g. a tool under investigation
      denied_argument_patterns: []      # regular expressions refused in any argument
      unmasked_tools: []                # tools whose results may carry personal data
```

The bank's rules are shared with the LLM gateway. A rule without `gateways` applies to both gateways; `"gateways": ["mcp"]` makes it apply to tool calls only. In the MCP gateway a `refuse` rule refuses the tool arguments and a `mask` rule masks tool results. The file is read again when it changes. See [Guardrails](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/guardrails.md) for the rule format.

```json
{
  "name": "sql-drop-table",
  "description": "A tool argument that would drop a table",
  "pattern": "(?i)\\bdrop\\s+table\\b",
  "action": "refuse",
  "gateways": ["mcp"]
}
```

## How a refusal looks to the client

A refused tool call is not an HTTP error. The client gets a normal JSON-RPC answer whose result is a tool error: `result.isError: true`, with a text that names the plugin and the code, for example `tool_pre_invoke blocked by plugin visdom-guard: VISDOM_SECRET …`. The client, and the model behind it, see the reason.

| Code or text             | Cause                                                                                              |
| ------------------------ | -------------------------------------------------------------------------------------------------- |
| `VISDOM_TOOL_DENIED`     | The tool is on `visdom-guard`'s deny-list.                                                         |
| `VISDOM_SECRET`          | A secret in the arguments.                                                                         |
| `VISDOM_BANK_RULE`       | One of the bank's refusing rules matched the arguments.                                            |
| `VISDOM_ARGUMENT_DENIED` | An argument matched `denied_argument_patterns`.                                                    |
| `RATE_LIMIT`             | Over a rate limit.                                                                                 |
| `PDP_DENY`               | The OPA policy denied the call, or OPA could not be reached; the text carries the policy's reason. |
| "exists but is inactive" | The tool or its tool server is switched off, or an emergency stop is in force.                     |

Token problems are HTTP errors: `401` for an unknown, expired or revoked token, `403` for a token of another virtual server.

## Rate limits

The `rate-limit` plugin counts in the gateway's Redis, so every worker and replica counts the same calls.

| Setting     | Default             | What it limits                                                                                                        |
| ----------- | ------------------- | --------------------------------------------------------------------------------------------------------------------- |
| `by_user`   | `600/m`             | Calls per owner of the client token.                                                                                  |
| `by_tool`   | none for real tools | Calls per tool, shared by every caller, by the tool's gateway name, for example `issue-tracker-create-issue: "30/m"`. |
| `algorithm` | `fixed_window`      | Also `sliding_window` or `token_bucket`.                                                                              |
| `fail_mode` | `open`              | When Redis cannot be reached, calls go through. `closed` refuses them instead.                                        |

{% hint style="warning" %}
Tokens issued in the console all belong to the MCP gateway's admin account, so `by_user` is in practice one ceiling for all console-issued clients together, not a limit per person or per client.
{% endhint %}

A call over a limit is answered with `isError` and the code `RATE_LIMIT`, not with HTTP `429`.

## OPA policy (optional)

The `opa-policy` plugin asks an Open Policy Agent server before every tool call and resource read. The policy is Rego in package `visdom.mcp`: the call goes on when `allow` is true, and the reasons in `deny` are shown to the client. The gateway ships an example to replace with your own rules:

```rego
package visdom.mcp

default allow := false

allow if count(deny) == 0

# Agents do not open issues in Risk Analytics: people raise those.
deny contains "agents may not create issues in project RISK: Risk Analytics issues are raised by people" if {
	input.resource.type == "tool"
	endswith(input.resource.id, "-create-issue")
	upper(input.context.tool_args.project) == "RISK"
}
```

| Input field               | Value                                                                                      |
| ------------------------- | ------------------------------------------------------------------------------------------ |
| `input.action`            | `tools.invoke.<tool>` or `resources.fetch`                                                 |
| `input.resource.type`     | `tool` or `resource`                                                                       |
| `input.resource.id`       | The tool's gateway name (`<server>-<tool>`) or the resource URI                            |
| `input.subject.email`     | The owner of the client token (for console-issued tokens, the MCP gateway's admin account) |
| `input.context.tool_args` | The tool call's arguments                                                                  |

Switch it on:

{% tabs %}
{% tab title="Docker Compose" %}

```bash
MCP_OPA_MODE=enforce          # enforce | permissive (log only) | disabled
MCP_OPA_URL=http://opa:8181   # default
```

```bash
docker compose --profile policy up -d
```

The `policy` profile starts OPA with the policies in `deploy/compose/contextforge/opa/`.
{% endtab %}

{% tab title="Helm" %}

```yaml
mcpGateway:
  plugins:
    opa:
      enabled: true
      mode: enforce        # enforce | permissive (log only)
      policy: |            # Rego of package visdom.mcp; empty uses the example policy
        package visdom.mcp
        ...
```

The chart then runs OPA with two replicas next to the MCP gateway, reachable only from it. `values-external.yaml` switches it on.
{% endtab %}
{% endtabs %}

{% hint style="danger" %}
With the plugin on `enforce`, every tool call is refused while OPA cannot be reached (`PDP_DENY`). The default decision is deny.
{% endhint %}

## Fail closed

The plugin framework runs with `fail_on_plugin_error: true`: a guardrail that fails blocks the call instead of letting it through. The OPA plugin denies when it gets no decision. The one deliberate exception is the rate limiter's `fail_mode: open`, which lets calls through when Redis is down; set it to `closed` if you prefer refusals.

## Kill switches

Switches act on the next call, with no restart; the gateway keeps its cache in Redis, so every replica sees the change. Each switch is an evidence record.

| Switch           | Where in the console                      | Role     | Effect                                                             |
| ---------------- | ----------------------------------------- | -------- | ------------------------------------------------------------------ |
| Tool             | **Catalogue**, the tool's switch          | admin    | The tool is refused on every virtual server.                       |
| Resource, prompt | **Catalogue**, Resources and Prompts tabs | admin    | The resource or prompt is no longer offered.                       |
| Tool server      | **MCP servers**, the server's switch      | admin    | Every tool of the server is refused.                               |
| Virtual server   | **Virtual servers**, the switch           | operator | The virtual server is switched off; its tools and tokens are kept. |
| Client token     | **Virtual servers → Clients → Revoke**    | operator | The client is refused (`401`) within 5 seconds.                    |
| Emergency stop   | **MCP servers → Emergency stop**          | admin    | Every tool server off at once.                                     |

## Emergency stop

The emergency stop switches every tool server off at once: agents and assistants get no tools until you resume. Use it when something is wrong and you do not yet know which server or tool.

{% stepper %}
{% step %}

### Stop

On **MCP servers**, select **Emergency stop**, then **Stop every tool server**. A red banner then says since when and by whom the gateway is stopped. Every tool call is refused.
{% endstep %}

{% step %}

### While stopped

You cannot register a tool server or switch one on; the console answers that the gateway is stopped. Everything else (the catalogue, virtual servers, tokens, approvals) can still be changed.
{% endstep %}

{% step %}

### Resume

Select **Resume** in the banner. Only the servers the stop switched off are switched on again; a server that was already off before the stop stays off, and a server deleted meanwhile is skipped. The console reports how many servers were enabled again.
{% endstep %}
{% endstepper %}

The stop is recorded first and the servers are switched off after, so a failure part way still leaves the gateway marked stopped. If a server could not be switched off, the console answers HTTP `502` naming it; switch it off by hand or try again. The stop is an evidence record (`mcp.emergency_stop`, with the servers it switched off), and so is the resume (`mcp.emergency_stop.resumed`). The stop also sends the notification `mcp.emergency_stop` by e-mail and to the chat webhook, where these are configured (see [Notifications](https://docs.visdom.virtuslab.com/visdom-ai-gateway/visdom-platform/notifications.md)).

The emergency stop covers the MCP gateway only. Models in the LLM gateway have their own kill switch; see [Model catalogue and providers](https://docs.visdom.virtuslab.com/visdom-ai-gateway/llm-gateway/model-catalogue.md).

```bash
curl -sS https://ai-gateway.example.com/api/mcp/emergency-stop -H "Authorization: Bearer $AUTOMATION_TOKEN"
# {"stop": null}  or  {"stop": {"at": "...", "by": "...", "serverIds": [...]}}

curl -sS -X POST https://ai-gateway.example.com/api/mcp/emergency-stop -H "Authorization: Bearer $AUTOMATION_TOKEN"
curl -sS -X POST https://ai-gateway.example.com/api/mcp/emergency-stop/resume -H "Authorization: Bearer $AUTOMATION_TOKEN"
# {"resumed": 2}
```
