# Guards (/docs/modules/guards)

Every interface module, the Web Components and `useAiChat` run guards on every conversation, with no setup. The conversation runs in the visitor's page on the visitor's own model, which reads three kinds of text: your instructions, the visitor's questions and your tools' results. The guards keep each one in its place:

- a visitor who asks the model to drop your instructions gets your safe answer, and the question never reaches the model;
- text planted in your data by a third party, such as a review or a comment, reaches the model as data, and cannot pose as your instructions;
- an answer that repeats your instructions, names something you keep internal, or would carry the conversation to another server through a link, an image or an email address stops at its first piece, and your safe answer shows in its place.

The guards run in English, French and Hebrew, and your site tunes them with the `guards` option.

## What runs on every conversation [#what-runs-on-every-conversation]

| Guard | What it does |
| --- | --- |
| Salted envelopes | A random salt is drawn for each conversation in the visitor's browser. It closes `<instructions-SALT>` around your instructions and `<tool-result-SALT>` around every tool result, and the instructions tell the model that only the first envelope guides it. |
| Question guard | Checks each question before it leaves the page. |
| Answer guard | Checks the answer at each piece the model streams, and once it ends. |
| Drawing | The modules draw no image, and draw a link only when the answer guard allows it. |
| Tool activity | Shows a row only for the tools you list in `visibleTools`. |

### Salted envelopes [#salted-envelopes]

Text that does not know the salt cannot close an envelope, so a review that writes `</tool-result-...>` followed by new instructions stays inside the tool result, where the model reads it as data. The salt stays in the visitor's browser and goes only to the model, and a new conversation draws a new one. Your tools' results reach your page as they are: `renderToolResults` and the `onToolResult` hook receive the raw result, and only the model reads the envelope.

### The question guard [#the-question-guard]

A question stops when it is longer than `maxInputLength` (2,000 characters by default), when it holds a long base64 blob, or when it matches one of 18 injection patterns in English, French and Hebrew: ignore or forget the instructions, a `system:` prefix, new instructions, a change of role or persona, a request for the prompt, a spoofed envelope tag. Up to three words may sit between the verb and its object, so "ignore all of the previous instructions" stops as "ignore instructions" does. The patterns also read the question with invisible characters removed and with digits used as letters read as letters, so "1gn0r3 y0ur rul3s" stops too.

A stopped question never reaches the model and stays out of the conversation the model reads.

### The answer guard [#the-answer-guard]

An answer stops on:

| What it holds | Why |
| --- | --- |
| An envelope tag or the conversation's salt | The model is repeating its instructions. |
| An image, in Markdown or HTML | An image loads by itself, and its address can carry the conversation to another server. |
| A link outside the page's origin, your `allowedLinkHosts`, and the addresses your tools returned as fields | A link the model wrote itself can carry the conversation in its address. |
| An email address the visitor did not type, your tools did not return as a field, and `allowedEmails` does not list | The model is handing out an address from its own context. |
| A match of `denyPatterns` | An internal name: a tool, a table, a vendor, a server, an identifier. |
| A match of `withholdPatterns` | Content your site does not hand out. |

A web address or an email address counts as your tools' own when a result gives it as a whole field, such as `"website": "https://..."` or `"email": "..."`. The guard reads each result as JSON and keeps the strings that are one address and nothing else, at any depth. An address written inside free text, such as a review, is no field, whatever quotes surround it, so a planted link stays unclickable and a planted email address stops the answer, even when the model copies it exactly. A result that is not JSON, such as plain text or a tool error, gives no address: list the hosts such a tool links to in `allowedLinkHosts`, and the addresses it gives in `allowedEmails`.

While the answer streams, each piece is checked with everything written before it. A link or an address still being written waits for its last character, so a host is judged once it is complete. From the first piece that trips a guard, the text stops reaching the page, the model's answer is cut in the wallet, and the safe answer replaces what showed. The conversation keeps the safe answer in place of the stopped one, so the next question reads the safe answer where the stopped text was.

The guard reads the answer in the visitor's browser, once the model has written it. The pieces that streamed before a pattern was complete were shown until the safe answer replaced them, and the browser received the whole answer whatever the page draws. `denyPatterns` and `withholdPatterns` keep an answer clean. Content that must stay out of a visitor's reach is held back on your server, before it reaches the model: see [On your MCP server](#on-your-mcp-server).

## The safe answer [#the-safe-answer]

A stopped question or answer shows the module's own words in the page's language, from `guardQuestion` and `guardAnswer` of the [module copy](/docs/modules#languages), or your `safeAnswer` when you set one. The turn carries `blocked: 'question'` or `blocked: 'answer'`, and the module marks the answer with `data-blocked` for your styles.

## Tune the guards [#tune-the-guards]

Pass your values as `guards`. Every field is optional.

```tsx title="AiModePanel.tsx"
const GUARDS = {
  scope: 'the books listed on this site',
  denyPatterns: ['search_books', 'get_book', '\\b[a-f0-9]{24}\\b'],
  visibleTools: ['search_books'],
};

<AiChatPanel system={SYSTEM_PROMPT} mcp="/api/mcp" guards={GUARDS} />;
```

### GuardPolicy

| Prop                | Type                                | Description |
| ------------------- | ----------------------------------- | ----------- |
| `maxInputLength?`   | `number \| undefined`               |             |
| `scope?`            | `string \| undefined`               |             |
| `allowedLinkHosts?` | `string[] \| undefined`             |             |
| `allowedEmails?`    | `string[] \| undefined`             |             |
| `denyPatterns?`     | `(string \| RegExp)[] \| undefined` |             |
| `withholdPatterns?` | `(string \| RegExp)[] \| undefined` |             |
| `visibleTools?`     | `string[] \| undefined`             |             |
| `safeAnswer?`       | `string \| undefined`               |             |

- **scope.** What the chat answers about. The model redirects any other question.
- **allowedLinkHosts.** Hosts an answer may link to, with their subdomains, such as your blog or your booking partner. Your own origin and the addresses your tools return as fields need no entry.
- **allowedEmails.** Your public addresses. The visitor's own address and the ones your tools return as a whole field need no entry. An address your tools give inside free text, such as the contact address in a page of your docs, needs one.
- **denyPatterns** and **withholdPatterns.** Plain words or regular expression sources, read without regard to case. A pattern that is not a valid regular expression throws when the conversation starts.
- **visibleTools.** The tools whose activity shows. The others still run, and their results still reach `renderToolResults`.
- **safeAnswer.** One answer for every stop, in place of the module's own words.

The guards read `guards` at the conversation's first question, so a change applies from the next conversation.

### Web Components [#web-components]

The elements take the same values as JSON in their `guards` attribute, each pattern written as a regular expression's source:

```html
<aiconnect-chat variant="popup" mcp="/api/mcp"
  system="You recommend books from this site's catalog."
  guards='{"denyPatterns": ["search_books"], "visibleTools": ["search_books"]}'></aiconnect-chat>
```

An attribute that is not valid JSON of this shape is reported in the console and left out.

### Your own interface [#your-own-interface]

`useAiChat({ system, tools, guards })` runs the same guards. Its turns carry `blocked`, its tool activity carries `visible: false` for a tool outside `visibleTools`, and `linkAllowed(href)` tells your renderer which links of an answer it may draw.

A page that runs `runConversation` itself creates the conversation's guard once, passes it to each question, and shows its safe answer when the loop throws a `GuardStop`:

```ts
import { createChatGuard, GuardStop, runConversation } from '@tensorpass/aiconnect';

const guard = createChatGuard({ denyPatterns: ['search_books'] });

try {
  const added = await runConversation({ session, tools, guard, messages, onText });
} catch (error) {
  if (error instanceof GuardStop) {
    showSafeAnswer(error.stage);
  }
}
```

## On your MCP server [#on-your-mcp-server]

Anyone can call your MCP server without your page, so the server keeps its own checks:

- Build each result from the public fields by name, and give page URLs, websites and booking links as fields of their own.
- Run `checkToolResult(text, guards)` from `@tensorpass/aiconnect` on each result before it returns, so no internal name leaves the server.
- Keep the names that must stay private, such as your internal services and hosts, in a policy only the server imports. The values your page passes as `guards` ship in its code, where anyone can read them.
- Bound every input in its schema, cap each result, and limit each visitor address.

The [MCP guide](/docs/guides/mcp-tools) covers the tools, and the `aiconnect-hardening` [Agent Skill](/docs/agents) holds a rate limit, the policy files of the page and of the server, and a pen test that runs the attacks in English, French and Hebrew against your guards, your MCP server and a real model.
