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

# Embed an AI assistant backed by your product's MCP server

> An agent-executable guide: put a web chat on any product that has an MCP server, powered by an agentic loop that uses tools authorized for the signed-in user

**Written for AI agents.** This guide is meant to be read and executed by an AI coding agent acting on behalf of a person who owns a product. Steps marked **🧑 Human action required** need the person: account sign-up, credentials, secret handling, production deploys and anything that changes who answers their customers. When you reach one, stop, tell the person exactly what to do and what to hand back to you, and continue only once you have it. Everything else you can do yourself.

## What you will build

By the end, a visitor on the product's website opens a chat launcher, is recognised as their signed-in account, and talks to an AI agent that answers with the product's own data by calling the product's MCP server with a token issued for **that visitor only**. Nothing in the flow uses a shared admin credential.

```
Visitor (signed in on your product)
   │  opens the chat launcher; the page carries a token your backend signed
   ▼
Web Widget channel (Chatbot Platform)
   │  new conversation → POST conversation.started to your webhook (signed)
   ▼
Your backend                     ──►  answers with MCP servers + per-user auth headers
   │                                  (and, optionally, preferences the agent should start with)
   │
   ▼
Agentic loop (OpenRouter model)  ──►  calls tools on your MCP server as that user
   │
   ▼
Reply appears in the widget
```

The platform pieces involved:

| Piece | Role |
| - | - |
| **Bot** | Owns the channel and the integration |
| **Web Widget channel** | The embeddable chat, visitor identity, allowed origins, MCP discovery webhook |
| **Agentic loop integration** ("AI agent") | The model that answers; sees every MCP server attached to the conversation |
| **MCP discovery webhook** | Your endpoint that maps a visitor to the MCP servers (and credentials) they may use, plus any **preferences** the agent should know from the first reply |
| **Widget Identity server** | A built-in MCP server you can use for a smoke test before your webhook exists |

## Human actions at a glance

Collect these up front so the person is not interrupted ten times:

| # | 🧑 Human action | Why it needs a human |
| - | - | - |
| 1 | Sign up / sign in at app.chatbotplatform.io and create or pick a team | Account ownership, email verification |
| 2 | Provide an **OpenRouter API key** for the team (or confirm one is set) | Billing credential |
| 3 | Approve the **system prompt**, model and **Only the agent answers** | Changes who replies to their customers |
| 4 | Copy the channel's **signing secret** and **MCP webhook secret** into the product's secret store | Secret handling policy |
| 5 | Deploy the product changes (webhook endpoint, token endpoint, embed snippet) | Production deploy approval |
| 6 | Run the end-to-end test as a real signed-in user, or let you drive a browser | Needs a logged-in session |

If you can drive a browser as the person (for example they are logged in to the dashboard in a session you control), you may perform the dashboard clicks yourself. Otherwise, hand them the exact clicks from each step.

## Step 0: Gather inputs

Ask the person for, or discover from the product's codebase:

* **Product name** and the public **site origin(s)** where the chat will appear, e.g. `https://app.acme.example`.
* **MCP server URL** of the product (Streamable HTTP, e.g. `https://api.acme.example/mcp`) and **how it authenticates**: usually `Authorization: Bearer <token>`. Confirm the product can **mint a token scoped to one user** with a limited lifetime. If it cannot yet, that is the first thing to build; see Step 6.
* **How users are identified** in the product (the stable user id you will put in the `sub` claim).
* Whether the chat should also work for **anonymous visitors**. Default for a product assistant: no.

Your MCP server must speak the Model Context Protocol over Streamable HTTP: JSON-RPC `initialize`, `tools/list` and `tools/call` on one URL. The platform passes the headers you return verbatim on every request, honours `Mcp-Session-Id`, and accepts plain JSON or `data:` SSE responses. Tool input schemas are normalised to what OpenRouter models accept, so standard JSON Schema is fine.

## Step 1: Account, team and bot

**🧑 Human action required.** The person signs up or signs in at [app.chatbotplatform.io](https://app.chatbotplatform.io/register) and selects the team that should own the assistant. Ask them to confirm the team name back to you.

Then create the bot (dashboard, under **Bots → Create Bot**): give it the product's name, e.g. "Acme Assistant". A bot is created with a default **Echo** integration that replies `You said: "…"`; the agent you launch in Step 3 replaces it.

## Step 2: Create the Web Widget channel

In the bot, open **Channels → Add channel → Web Widget** and fill in:

| Field | Value to use |
| - | - |
| Channel Name | `Website chat` |
| Widget Title | Product name, e.g. `Acme` |
| Agent name | A persona, e.g. `Ava from Acme` (optional) |
| Greeting | e.g. `Hi! Ask me anything about your account.` |
| Allow anonymous visitors | **Off** (the assistant acts for signed-in users) |
| Allowed origins | The product origins from Step 0, one per line |
| MCP servers for conversations | Leave empty for now |

Click **Create Web Widget**. The channel page opens; note three things on it for later:

* the **embed snippet** (`<script src="https://app.chatbotplatform.io/widget/widget.js" data-widget-key="…" async>`),
* the **widget key** under it,
* the **signing secret** in the *Signing secret* block.

**🧑 Human action required.** Ask the person to copy the **signing secret** from the channel page into the product's secret store as `CHATBOT_WIDGET_SECRET`. Do not paste it into chat logs or commit it.

## Step 3: Launch the AI agent with the built-in test server

At the top of the channel page, **Power this chat with an AI agent** is open. Set:

1. **System prompt** — start from the template (**Use template**) and add product context. Keep the line that tells the model to call `whoami` for identity questions; add one about your product's tools, for example:

   ```
   You are Acme's assistant on the website chat. Be concise, friendly and accurate.

   Tools may be attached to this conversation. Use them whenever they can answer the question instead of guessing:
   - When the visitor asks who they are, what their email address is, or anything about their account, call the whoami tool and answer from its result.
   - For orders, invoices and subscriptions use the Acme tools; they already act as the signed-in user.
   - If a question needs data you do not have and no tool provides it, say so and suggest how the person can get help.

   Never invent account details, prices or policies. Keep answers short unless asked for detail.
   ```

2. **Model** — any tool-capable model from the OpenRouter list (for example `openai/gpt-4o-mini`). The preselected default is a free model; prefer a paid, tool-reliable one for production.

3. **OpenRouter API key** — the field is shown only while the team has no key.

   **🧑 Human action required.** An OpenRouter API key is a billing credential and only a team **owner or admin** can save it. Ask the person to paste it here, or to add it under **Agent loops → Settings** in the dashboard, and to confirm when done.

4. **Tools for each visitor (MCP servers)** — choose **Built-in test server (Widget Identity) until my webhook is ready**.

5. **Only the agent answers** — leave ticked, so the default Echo integration (and any other webhook) is switched off.

**🧑 Human action required.** Show the person the prompt, the model and the **Launch will** summary (it lists exactly what changes, including which integrations get switched off). Launch only after they approve.

Click **Launch agent**. The platform creates an agentic-loop integration named **AI agent** on the bot (relaunching later updates it rather than duplicating it), disables competing integrations, saves the key, points **MCP servers for conversations** at the built-in test webhook and mints its secret. The section shows a **Live** badge.

## Step 4: Smoke-test the pipeline

Still on the channel page, **Test your web chat** lists a readiness checklist (channel enabled, integration, OpenRouter key, MCP servers, identity). All rows should be green.

**🧑 Human action required** unless you can drive the browser: click **Start test chat**, which embeds the real widget signed in as the current dashboard user, and send **What is my email address?**

Expected: the bot calls `whoami` on the Widget Identity server and answers with the account's email. Then open **See the conversation in admin → MCP servers** tab: *MCP discovery webhook: OK* and **Widget Identity · Discovered · 2 tool(s)**.

If the reply is `You said: "…"` the Echo integration still answers — relaunch with **Only the agent answers** ticked. If the bot says it cannot know, the conversation was started before discovery was configured — start a new one with the widget's **+** button.

You now have proof that *identity → webhook → MCP → agent → reply* works. The rest replaces the built-in test server with the product's own.

## Step 5: Build the MCP discovery webhook in the product

Add an endpoint to the product's backend, e.g. `POST /chatbot/mcp-servers`. For every **new** conversation the platform POSTs a `conversation.started` event (and `conversation.test` when someone clicks **Send test request**). The endpoint must:

1. **Verify the signature.** Headers: `X-Chatbot-Timestamp` (unix seconds) and `X-Chatbot-Signature: v1=<hex HMAC-SHA256 of "timestamp.raw_body">` using the channel's **MCP webhook secret** (shown on the channel page once a URL is saved). Reject timestamps older than 5 minutes and compare signatures in constant time.
2. **Look up the visitor** from `user.id`, which is exactly the `sub` you put in the identity token (Step 6). For `user.anonymous === true` return an empty list.
3. **Mint a token scoped to that user** for your MCP server — short-lived, limited to what the assistant may do. Never return a global or admin credential.
4. **Answer** `200` with the servers to attach. Up to 20; an empty list is valid. Optionally add a `preferences` list with what the product already knows about the visitor (timezone, how to address them, plan limits) so the agent starts the conversation informed; see *Preferences* below. The whole call must finish within **10 seconds** (one retry on failure); a failing webhook never blocks the conversation, it just starts without your tools (and without your preferences).

### What the platform sends

```json theme={null}
{
  "event": "conversation.started",
  "bot": { "id": 1, "name": "Acme Assistant" },
  "channel": { "id": "<widget key>", "name": "Website chat" },
  "conversation": { "id": "<uuid>", "api_key": "conv_…", "created_at": "2026-10-28T10:00:00+00:00" },
  "user": {
    "id": "<sub from your token, or a visitor id>",
    "email": "ana@example.com",
    "name": "Ana Lima",
    "anonymous": false,
    "attributes": { "plan": "pro" }
  },
  "page": { "url": "https://app.acme.example/billing", "title": "Billing" }
}
```

`event` is `conversation.started` for a new conversation, `conversation.test` for the **Send test request** button and `conversation.refresh` when the agent calls `refresh-mcp-servers` or an admin clicks **Re-run discovery**. The request never carries preferences; they only travel in your answer.

`conversation.api_key` is the conversation's own key on the platform. Echo it back as the bearer token for the **Widget Identity** server to keep `whoami` available alongside your tools, or drop that entry once your own tools cover the user's details.

### What you answer

```json theme={null}
{
  "mcp_servers": [
    {
      "name": "Acme",
      "url": "https://api.acme.example/mcp",
      "headers": [ { "key": "Authorization", "value": "Bearer <token minted for user.id>" } ],
      "expires_at": "2026-11-09T15:00:00Z"
    },
    {
      "name": "Widget Identity",
      "url": "https://app.chatbotplatform.io/mcp/widget-identity",
      "headers": [ { "key": "Authorization", "value": "Bearer <conversation.api_key from the request>" } ]
    }
  ],
  "preferences": [
    "User's timezone for dates and times: America/Chicago",
    "Address the user as Ana",
    "The user is on the Pro plan (up to 10 projects)"
  ]
}
```

Each entry in `mcp_servers` needs a `name` (≤ 255 characters, unique; a later duplicate replaces an earlier one) and an http(s) `url`; `headers` are optional, and so is an expiry for the credentials (next section).

### Expiring credentials (optional)

The tokens you hand out in `headers` are usually short-lived. Tell the platform when they run out and it refreshes them for you **before** the agent needs them, instead of letting the first tool call fail with a 401 and relying on the agent to call `refresh-mcp-servers`.

| Field (per server) | Type | Rules |
| - | - | - |
| `expires_at` | ISO 8601 timestamp, optional | When this server's credentials stop working. Any timezone offset is accepted. |
| `ttl_seconds` | positive integer, optional | The same, counted from the moment your answer is received. At most one year (31 536 000). `expires_at` wins when both are present. |

What happens with it:

* **Refresh before the reply.** Each time a visitor message or a fired reminder is about to be answered, the platform checks the servers your webhook discovered for that conversation. If one expires within the next **5 minutes**, or has already expired, it calls your webhook again with `conversation.refresh` (the same body as `conversation.started`) and only then builds the agent's tool list. Servers are matched by `name` and updated in place; a running agent loop picks the new credentials up on its next tool call. The whole process adds one webhook round trip to that reply, nothing to the others.
* **Your answer sets the next expiry.** Return the new token with a new `expires_at` / `ttl_seconds` and the cycle continues. Leave both keys out and that server is never refreshed on its own again.
* **A failed refresh never blocks the reply.** If your webhook is down or answers with an invalid body, the platform logs it, keeps the servers it discovered earlier (the agent can still try them, and `refresh-mcp-servers` remains available) and waits at least one minute before refreshing that conversation again. The **MCP servers** tab records the failed `conversation.refresh` like any other discovery outcome.
* **No expiry, no refresh.** Servers without the fields behave exactly as before: they stay until the agent, an admin or your own `conversation.refresh` answer replaces them.

Mint tokens that outlive a conversation turn comfortably (an hour is typical) rather than ones that expire in a minute: the 5-minute window means a token shorter than that is refreshed on every message.

### Preferences (optional)

Next to the servers, the same response may carry a `preferences` list: short, free-form sentences the platform records as the conversation's **preferences** before the first reply. Preferences are the per-conversation notes the agent keeps about the person (see **Conversation Preferences** under *Tools the agent always has*); they are listed in the agent's system prompt on every turn, so facts you already hold (timezone, preferred name, plan, limits, language) reach the model without a tool call. The key only exists on the **response**. The `conversation.started` request never contains it.

| Field | Type | Rules |
| - | - | - |
| `preferences` | array of strings, optional | Up to **20** entries of at most **1000 characters** each. Entries are trimmed, blank ones dropped and duplicates (case-insensitive) collapsed to the first occurrence; anything past the 20th is ignored. Leave the key out or send `null` to pre-fill nothing. |

How the list is applied:

* **Merge, never overwrite.** Each entry whose text is not already recorded for the conversation (compared trimmed and case-insensitively) is added, in the order you returned it. Existing preferences, whether the bot recorded them through the Conversation Preferences tools, an admin edited them, or an earlier discovery pre-filled them, are never changed or removed. A `conversation.refresh` can therefore top the list up but cannot undo what the conversation has learnt since.
* **Ordinary preferences afterwards.** Pre-filled entries behave like any other: the bot can revise or delete them with its tools and admins can edit them on the conversation's **Preferences** tab.
* **Ignored when preferences are off.** If the bot's **Preferences** switch (Behavior settings) is off, the servers are still attached and the list is dropped; the discovery outcome records `preferences_skipped: preferences_disabled`.
* **Shape errors fail the whole response.** A `preferences` value that is not an array of strings, or an entry over 1000 characters, is a contract violation like a bad `mcp_servers` entry: the platform logs a failure and the conversation starts **without your servers too**. Validate what you send.

Write each entry as a complete sentence the model can act on (*"User's timezone for dates and times: America/Chicago"*), not a key-value fragment. Keep credentials and anything the visitor should not see out of it: preferences are shown in the admin dashboard and can be read back by the bot.

### Skills (optional)

The response may also carry a `skills` list: processes the platform saves as [skills](https://docs.chatbotplatform.io/bots/channels/user-skills.md) of the **person** behind the conversation, so the agent can follow your product's playbooks by name from the first reply. Like `preferences`, the key only exists on the **response**.

```json theme={null}
{
  "mcp_servers": [ { "name": "Acme", "url": "https://app.acme.example/mcp" } ],
  "skills": [
    {
      "name": "weekly-report",
      "summary": "Build and post the weekly sales report",
      "content": "1. Fetch last week's orders with the Acme tools.\n2. Summarise them per region.\n3. Present a table, totals last."
    }
  ]
}
```

| Field | Type | Rules |
| - | - | - |
| `skills` | array of objects, optional | Up to **20** entries; anything past the 20th is ignored. Leave the key out or send `null` to seed nothing. |
| `skills[].name` | string, required | A slug of 2 to 64 lowercase letters, digits and dashes. Upper case is lowered; two entries with one name keep the last. |
| `skills[].summary` | string, required | One line, up to **200 characters**. This is what the agent sees in its system prompt. |
| `skills[].content` | string, required | Up to **20 000 characters**: the steps, the tools each step calls and how to present the result. |

How they are applied:

* **Create only, never overwrite.** A name the person does not have yet is created at version 1 and listed in every conversation they own, on every linked channel. A skill of that name they already have (taught in chat, edited since, or seeded earlier) is left exactly as it is, so send the same list with every response.
* **Deleting sticks.** A seeded skill the person deleted is not created again while the deleted copy is kept (30 days).
* **Ordinary skills afterwards.** The person can update or delete a seeded skill in chat; admins see it on the person's page under **People**.
* **Ignored when skills are off.** If the bot's **Skills** switch (Behavior → Agent Context) is off, the servers are still attached and the list is dropped; the discovery outcome records `skills_skipped: skills_disabled`.
* **At the limit.** A person can hold 50 skills; entries that would exceed it are skipped and the rest are saved.
* **Shape errors fail the whole response.** A `skills` value that is not an array of `{name, summary, content}` objects, a name that is not a slug or a field over its limit is a contract violation: the conversation starts **without your servers too**.

**Send test request** lists the skills your webhook returned (*It also sent N skill(s) to save for the person behind each new conversation*) without storing them, and the conversation's **MCP servers** tab reads *saved N of M skill(s) for this person* after a real discovery; N is lower than M when the person already had some.

> [accordion] Webhook — Node (Express)
>
> ```javascript theme={null}
> import express from 'express';
> import crypto from 'node:crypto';
>
> const SECRET = process.env.CHATBOT_MCP_WEBHOOK_SECRET; // from the channel page
> const app = express();
>
> function signatureMatches(expected, actual) {
>   const a = Buffer.from(expected), b = Buffer.from(actual || '');
>   return a.length === b.length && crypto.timingSafeEqual(a, b);
> }
>
> app.post('/chatbot/mcp-servers', express.raw({ type: 'application/json' }), async (req, res) => {
>   const timestamp = req.header('X-Chatbot-Timestamp');
>   const expected = 'v1=' + crypto.createHmac('sha256', SECRET)
>     .update(`${timestamp}.${req.body.toString('utf8')}`).digest('hex');
>
>   if (!timestamp || Math.abs(Date.now() / 1000 - Number(timestamp)) > 300
>       || !signatureMatches(expected, req.header('X-Chatbot-Signature'))) {
>     return res.status(401).json({ error: 'bad signature' });
>   }
>
>   const event = JSON.parse(req.body.toString('utf8'));
>   if (event.user.anonymous) return res.json({ mcp_servers: [] });
>
>   const user = await users.findById(event.user.id); // event.user.id === the `sub` you signed
>   if (!user) return res.json({ mcp_servers: [] });
>
>   // A token that lets the assistant act only as this user, for a limited time.
>   const token = await mintMcpToken(user, { ttlSeconds: 24 * 3600, scope: 'assistant' });
>
>   res.json({
>     mcp_servers: [
>       { name: 'Acme', url: 'https://api.acme.example/mcp',
>         headers: [{ key: 'Authorization', value: `Bearer ${token}` }] },
>       { name: 'Widget Identity', url: 'https://app.chatbotplatform.io/mcp/widget-identity',
>         headers: [{ key: 'Authorization', value: `Bearer ${event.conversation.api_key}` }] },
>     ],
>     // Optional: what the agent should know before its first reply (≤ 20 entries, ≤ 1000 chars each).
>     preferences: [
>       `User's timezone for dates and times: ${user.timezone}`,
>       `Address the user as ${user.firstName}`,
>       `The user is on the ${user.plan} plan`,
>     ],
>   });
> });
> ```

> [accordion] Webhook — PHP
>
> ```php theme={null}
> <?php
> $secret = getenv('CHATBOT_MCP_WEBHOOK_SECRET'); // from the channel page
> $timestamp = $_SERVER['HTTP_X_CHATBOT_TIMESTAMP'] ?? '';
> $body = file_get_contents('php://input');
>
> $expected = 'v1=' . hash_hmac('sha256', "$timestamp.$body", $secret);
> if ($timestamp === '' || abs(time() - (int) $timestamp) > 300
>     || ! hash_equals($expected, $_SERVER['HTTP_X_CHATBOT_SIGNATURE'] ?? '')) {
>     http_response_code(401);
>     exit;
> }
>
> $event = json_decode($body, true);
> header('Content-Type: application/json');
>
> if ($event['user']['anonymous'] || ! ($user = User::find($event['user']['id']))) {
>     echo json_encode(['mcp_servers' => []]);
>     exit;
> }
>
> $token = mintMcpToken($user, ttlSeconds: 86400, scope: 'assistant');
>
> echo json_encode([
>     'mcp_servers' => [
>         ['name' => 'Acme', 'url' => 'https://api.acme.example/mcp',
>          'headers' => [['key' => 'Authorization', 'value' => "Bearer $token"]]],
>         ['name' => 'Widget Identity', 'url' => 'https://app.chatbotplatform.io/mcp/widget-identity',
>          'headers' => [['key' => 'Authorization', 'value' => 'Bearer ' . $event['conversation']['api_key']]]],
>     ],
>     // Optional: what the agent should know before its first reply (≤ 20 entries, ≤ 1000 chars each).
>     'preferences' => [
>         "User's timezone for dates and times: {$user->timezone}",
>         "Address the user as {$user->first_name}",
>         "The user is on the {$user->plan} plan",
>     ],
> ]);
> ```

> [accordion] Webhook — Python (Flask)
>
> ```python theme={null}
> import hmac, hashlib, os, time
> from flask import Flask, request, jsonify
>
> SECRET = os.environ["CHATBOT_MCP_WEBHOOK_SECRET"].encode()  # from the channel page
> app = Flask(__name__)
>
> @app.post("/chatbot/mcp-servers")
> def mcp_servers():
>     timestamp = request.headers.get("X-Chatbot-Timestamp", "")
>     body = request.get_data()  # raw bytes, exactly as sent
>     expected = "v1=" + hmac.new(SECRET, f"{timestamp}.".encode() + body, hashlib.sha256).hexdigest()
>
>     if (not timestamp or abs(time.time() - int(timestamp)) > 300
>             or not hmac.compare_digest(expected, request.headers.get("X-Chatbot-Signature", ""))):
>         return jsonify(error="bad signature"), 401
>
>     event = request.get_json(force=True)
>     if event["user"]["anonymous"]:
>         return jsonify(mcp_servers=[])
>
>     user = users.find_by_id(event["user"]["id"])  # == the `sub` you signed
>     if user is None:
>         return jsonify(mcp_servers=[])
>
>     token = mint_mcp_token(user, ttl_seconds=86400, scope="assistant")
>     return jsonify(
>         mcp_servers=[
>             {"name": "Acme", "url": "https://api.acme.example/mcp",
>              "headers": [{"key": "Authorization", "value": f"Bearer {token}"}]},
>             {"name": "Widget Identity", "url": "https://app.chatbotplatform.io/mcp/widget-identity",
>              "headers": [{"key": "Authorization", "value": f"Bearer {event['conversation']['api_key']}"}]},
>         ],
>         # Optional: what the agent should know before its first reply (<= 20 entries, <= 1000 chars each).
>         preferences=[
>             f"User's timezone for dates and times: {user.timezone}",
>             f"Address the user as {user.first_name}",
>             f"The user is on the {user.plan} plan",
>         ],
>     )
> ```

**Personal authorization is the point.** The token you return is what the model uses for every tool call in that conversation, so scope it to the one user and to read-mostly operations. If a tool performs a consequential action (refund, cancel, delete), have your MCP server require an explicit confirmation argument or keep it out of the assistant's scope.

## Step 6: Identify visitors and embed the widget

Two product changes so visitors are recognised:

### 6a. Mint the identity token

Add a backend endpoint (e.g. `GET /api/chat-widget-token`) that returns a token for the signed-in user. It is an **HS256 JWT** signed with `CHATBOT_WIDGET_SECRET` from Step 2:

| Claim | Required | Value |
| - | - | - |
| `sub` | Yes | Your stable user id (string, ≤ 255 chars). This is the `user.id` your webhook receives. |
| `exp` | Yes | Unix timestamp, at most 24 hours ahead. One hour is a good default. |
| `name`, `email` | No | Shown in the dashboard and returned by `whoami` |
| `attributes` | No | JSON object ≤ 4 KB, e.g. `{ "plan": "pro", "account_id": "acc_42" }`; also delivered to your webhook |

```javascript theme={null}
// Node: npm install jsonwebtoken
import jwt from 'jsonwebtoken';

app.get('/api/chat-widget-token', requireLogin, (req, res) => {
  const token = jwt.sign(
    { sub: String(req.user.id), name: req.user.name, email: req.user.email,
      attributes: { plan: req.user.plan } },
    process.env.CHATBOT_WIDGET_SECRET,
    { algorithm: 'HS256', expiresIn: '1h' },
  );
  res.json({ token });
});
```

PHP and Python versions are on the [Web Widget channel page](https://docs.chatbotplatform.io/bots/channels/web-widget.md#identify-your-users).

### 6b. Add the snippet

On every page where the launcher should appear, before `</body>`:

```html theme={null}
<script src="https://app.chatbotplatform.io/widget/widget.js" async></script>
<script>
  window.addEventListener('load', function () {
    ChatbotWidget.init({
      key: 'YOUR_WIDGET_KEY',            // from the channel page
      getUserToken: async () => {        // called on load and again when a token expires
        const res = await fetch('/api/chat-widget-token');
        return (await res.json()).token;
      },
    });
  });
</script>
```

For server-rendered pages you can instead render the token into the one-line snippet as `data-user-token="…"`.

**🧑 Human action required.** Deploying the webhook (Step 5), the token endpoint and the snippet changes the product. Open a pull request with the changes, summarise them, and ask the person to review, deploy to the environment they want to test in, and tell you the public **webhook URL** once it is reachable over HTTPS.

## Step 7: Point the channel at the product's webhook

Back on the channel page, either relaunch from **Power this chat with an AI agent** choosing **My webhook URL**, or expand **MCP servers for conversations** in the channel form and set **Webhook URL** to the endpoint from Step 5. Save.

The **Webhook secret** field now shows the secret that signs every request to your endpoint.

**🧑 Human action required.** Ask the person to copy the **MCP webhook secret** into the product's secret store as `CHATBOT_MCP_WEBHOOK_SECRET` and redeploy or restart so the webhook verifies with it.

Click **Send test request**. The platform sends a signed `conversation.test` to your URL and shows the answer: you should see your server name(s) listed (for example `2 MCP server(s)` with **Acme** and **Widget Identity**) and, when you return preferences, *It also sent N preference(s) to pre-fill each new conversation with* followed by the entries. A `401` means the secret in the product does not match; a `422`-style validation error means the response shape is off — compare it with *What you answer* above.

## Step 8: Verify end to end

**🧑 Human action required** unless you can drive a browser signed in to the product: on the product site, open the chat, start a **new** conversation and ask something only the product's tools can answer, e.g. *"What is my current plan and when does it renew?"*

Then in the dashboard, open the bot's **Conversations**, pick the newest one and check:

* **Widget user** matches the signed-in account (`sub`, name, email, attributes).
* **MCP servers** tab: *MCP discovery webhook: OK*, your server listed as **Discovered**, status **passing** with its tool count and, when you returned an expiry, *Expires in …* (amber once inside the refresh window, red once passed). **failing** means the platform could not complete `initialize`/`tools/list` against your URL with the headers you returned. When the webhook returned preferences the outcome line also reads *pre-filled N of M preference(s)*; N is lower than M only when some texts were already recorded.
* **Preferences** tab (shown while the bot's Preferences switch is on): the entries from your webhook, editable like any the bot recorded itself.
* The transcript shows the tool call and an answer grounded in it.

**Re-run discovery** on that tab replays the webhook (`conversation.refresh`) for an existing conversation; it replaces only the servers the webhook discovered earlier and leaves ones added through chat or the admin UI alone. Preferences in the new answer are merged the same way as on start: new texts are added, nothing already recorded is touched.

## Step 9: Go-live checklist

Walk through this with the person before announcing the chat:

* [ ] **Allowed origins** lists only the production origins.
* [ ] **Allow anonymous visitors** is off (or deliberately on, with the webhook returning no privileged servers for `anonymous: true`).
* [ ] **Only the agent answers** — the Integrations tab shows the **AI agent** as the only enabled integration.
* [ ] The system prompt names the product's tools and forbids inventing account data.
* [ ] A paid, tool-reliable model is selected and the OpenRouter key has credit.
* [ ] Secrets live in the secret store; neither appears in the repo, logs or chat history.
* [ ] Tokens from the webhook are per-user, short-lived and read-mostly.
* [ ] Someone knows where **Regenerate** lives for both secrets (channel page) and that rotating invalidates existing tokens immediately.

## Reference

### Tools the agent always has

Besides the servers your webhook returns, every agentic loop on the platform can use built-in tools attached to the conversation automatically: **Time** (date/time helpers), **Conversation Context** (archives and reminders, when enabled in the bot's Behavior settings), **Async Callbacks**, **Conversation Preferences** (when enabled in Behavior settings; the same per-conversation list your webhook's `preferences` seeds, which the bot reads in its system prompt and can add to, revise or delete) and **Conversation MCP Management** (lets the visitor add their own MCP servers by chatting). Servers configured bot-wide under the bot's **MCP Servers** tab are added too. On a name clash the conversation-level server wins over the bot-level one.

### Where each secret lives

| Secret | Shown | Used by |
| - | - | - |
| Signing secret | Channel page → *Signing secret* | Your backend, to sign identity tokens |
| MCP webhook secret | Channel page → *MCP servers for conversations* | Your backend, to verify discovery requests |
| OpenRouter API key | Agent loops → Settings (team-wide) | The platform, to run the agent |
| Conversation API key | In the webhook payload (`conversation.api_key`) | Bearer token for the platform's own conversation-scoped MCP servers |

### Error codes you may see

| Where | Code | Meaning |
| - | - | - |
| Widget requests | `401 token_expired` | Token `exp` passed; the widget asks `getUserToken` for a new one |
| Widget requests | `401 token_invalid` | Bad signature, wrong `alg`, missing `sub`, `exp` more than 24 h ahead |
| Widget requests | `401 token_required` | Anonymous visitors are off and no token was sent |
| Widget requests | `409 conversation_closed` | Message sent to a closed conversation |
| Discovery webhook (test) | `HTTP 401` from your endpoint | Secret mismatch |
| Conversation → MCP servers tab | status **failed** | Webhook unreachable, non-2xx, invalid JSON, bad `mcp_servers` shape, or `preferences` that is not an array of strings (≤ 1000 characters each) |
| Conversation → MCP servers tab | `preferences_skipped: preferences_disabled` | Servers attached, preferences dropped because the bot's Preferences switch is off |
| Conversation → MCP servers tab | `skills_skipped: skills_disabled` | Servers attached, skills dropped because the bot's Skills switch is off |
| Conversation → MCP servers tab | status **failed**, event `conversation.refresh` | An automatic or manual refresh failed; the previously discovered servers stay in place |

## Troubleshooting

| Symptom | Fix |
| - | - |
| **Needs setup** on the test panel | Follow the red row's link: enable the channel, launch the agent, or add the OpenRouter key. |
| Reply is `You said: "…"` | Echo still answers. Relaunch with **Only the agent answers**. |
| Bot does not know the user even with Widget Identity | Conversation pre-dates the webhook. Start a new one, or **Re-run discovery**. |
| Your server shows **failing** | The platform could not reach it or `tools/list` errored. Check the URL is public HTTPS, the header you returned is accepted, and the server answers JSON-RPC `initialize`. |
| `Send test request` → 401 | The product verifies with an old or wrong secret. Copy the current one from the channel page. |
| Launcher missing on the product site | Origin not in **Allowed origins**, or the script tag did not load. |
| Model ignores the tools | Pick a stronger tool-capable model; make the prompt name the tool and when to use it. |
| Tool calls fail with 401 after a while | Return `expires_at` or `ttl_seconds` with each server so the platform refreshes the token before the reply, or make the agent's prompt mention `refresh-mcp-servers`. |
| Preferences from the webhook do not show on the conversation | The bot's **Preferences** switch (Behavior settings) is off, the texts were already recorded (same text, any case), or the response failed validation and the servers are missing too. Check the *MCP servers* tab outcome line. |

## Next steps

> [card] [Web Widget channel reference](https://docs.chatbotplatform.io/bots/channels/web-widget.md)
>
> Every setting, the JavaScript API and the identity token contract

> [card] [Agentic Loops](https://docs.chatbotplatform.io/agentic-loops/overview.md)
>
> How the model reasons over tools

> [card] [MCP Servers](https://docs.chatbotplatform.io/mcp-servers/overview.md)
>
> The platform's built-in servers and their tools

> [card] [Bot Behaviors](https://docs.chatbotplatform.io/bots/behaviors/index.md)
>
> Typing indicators, debouncing, memory and preferences


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.