# Niotio — complete documentation

> Everything an agent needs in one file: the product summary, the REST API, the CLI, webhooks and the MCP server. Assembled at request time from the same sources as /llms.txt, /api/docs.md, /cli.md, /webhooks.md and /mcp.md, so it cannot drift from them. Machine-readable spec: https://niotio.dk/api/openapi.json

---

# Niotio

> Niotio is a web app for running Net Promoter Score (NPS) surveys: create a campaign, add respondents, email them a 0-10 survey, and read NPS metrics and comments. English and Danish UI.

- MCP server (recommended for agents): https://niotio.dk/mcp speaks the Model Context Protocol (JSON-RPC 2.0 over HTTP) with 35 tools that mirror the REST API and the CLI exactly — campaigns, metrics, email usage, respondents, survey responses, comment tags and comment search, and the follow-up cases behind every detractor. Authenticate with `Authorization: Bearer <API_TOKEN>`.
- REST API base URL: https://niotio.dk/api. Same token; users create tokens in the web app under Settings, and the raw token is shown once. Comment tags are first-class: search comments by text, tag, AI-vs-human source, rating and dates (`GET /api/comments`), and tag or untag one comment without replacing the rest.
- CLI: the `niotio` binary drives the same API. Configure it with the `NPS_URL` and `NPS_TOKEN` environment variables (or `niotio config`). Add `--json` for machine-readable output; destructive commands need `--yes` when non-interactive.
- Webhooks (Pro and Business): campaign and case events are POSTed to your URL, signed with an `X-NPS-Signature` header.
- Plans: Free 0 DKK/mo (100 survey emails, 1 seat, Niotio branding); Start 299 DKK/mo (1,000 emails, 2 seats); Pro 499 DKK/mo (3,000, 5 seats, webhooks, detractor case workflow, opt-in overage 15 DKK per 100); Business 999 DKK/mo (10,000, 15 seats, white label, overage). Yearly = 2 months free. Prices excl. VAT. API, CLI and MCP server on all plans. Paid plans are arranged by contacting us; no online payment yet.

## Docs

- [API docs](https://niotio.dk/api/docs.md): endpoints, auth, curl examples, email usage endpoint
- [OpenAPI spec](https://niotio.dk/api/openapi.json): every endpoint as an OpenAPI 3.1 document — auth scheme, path and query parameters, responses; generated from the same endpoint list as the API docs
- [Full docs in one file](https://niotio.dk/llms-full.txt): the product summary, API, CLI, webhooks and MCP in a single file
- [CLI guide](https://niotio.dk/cli.md): install, configuration, commands, scripting and exit codes
- [MCP server](https://niotio.dk/mcp.md): endpoint, client setup, tool reference, error shape
- [Webhooks](https://niotio.dk/webhooks.md): event envelope, X-NPS-Signature verification, retries, recipes

## Product

- [Pricing](https://niotio.dk/pricing): plans and prices excl. VAT (monthly or yearly; paid plans via contact, no online payment yet)
- [Landing page](https://niotio.dk/): what Niotio does, and how an agent connects over MCP
- [About](https://niotio.dk/about): who builds Niotio — one human founder and a team of AI assistants (labelled as bots, AI-generated portraits); what Niotio does today


## B2B service companies

- [NPS for service businesses](https://niotio.dk/nps-for-servicevirksomheder): how Danish service companies run NPS surveys and follow up on the answers
- [What is NPS?](https://niotio.dk/guides/nps-definition): the single 0-10 question, the three groups, and what the score does and does not say
- [How to calculate NPS](https://niotio.dk/guides/nps-beregning): promoters minus detractors, with a worked example and the caveats
- [NPS questions and templates](https://niotio.dk/guides/nps-spoergsmaal): wording, a short email template, timing and follow-up


## Optional

- [API docs (HTML)](https://niotio.dk/api/docs): the same API reference as a web page
- [CLI docs (HTML)](https://niotio.dk/cli): the CLI install page
- [MCP docs (HTML)](https://niotio.dk/mcp/docs): the MCP how-to as a web page
- [CLI installer](https://niotio.dk/cli/install.sh): `curl -fsSL https://niotio.dk/cli/install.sh | sh`


---

# Niotio REST API

> Niotio REST API. Base URL: `https://niotio.dk/api`

Authenticate with `Authorization: Bearer <API_TOKEN>`. Create a token in the web app under Settings → API Tokens; the raw token is shown only once. Responses are JSON.

Machine-readable spec: `https://niotio.dk/api/openapi.json` (OpenAPI 3.1, generated from this endpoint list). Everything in one file: `https://niotio.dk/llms-full.txt`.

## Errors

Every /api/** error is JSON (Content-Type: application/json) with error, kind: "api" and status. Unauthenticated calls return {"error":"HTTP 401","kind":"api","status":401}. A wrong method on a known path returns 405 with an Allow header; an unsupported Content-Type returns 415; an unknown path returns 404 — each with the same shape. Invalid ids, query parameters or JSON return 400 {"error":"bad_request","kind":"api","status":400} and include the parameter name when it is known. A missing campaign or case returns 404 with a short error message; another account's campaign is indistinguishable from a missing one.

## Endpoints

| Method | Path | Auth | Description |
| --- | --- | --- | --- |
| GET | `/api/campaigns` | Bearer token | List campaigns (`?test=true\|false`; `?trash=true` lists the caller's trash) |
| GET | `/api/campaigns/{id}` | Bearer token | Get a campaign by id |
| POST | `/api/campaigns` | Bearer token | Create a campaign |
| PUT | `/api/campaigns/{id}` | Bearer token | Update a campaign |
| DELETE | `/api/campaigns/{id}` | Bearer token | Move a campaign to the trash (204). It can be restored for 30 days; trashed campaigns are listed with ?trash=true. |
| POST | `/api/campaigns/{id}/restore` | Bearer token | Restore a trashed campaign (204) |
| POST | `/api/campaigns/{id}/activate` | Bearer token | Activate a campaign so it can send and collect responses; returns the campaign |
| POST | `/api/campaigns/{id}/deactivate` | Bearer token | Close a campaign; returns the campaign |
| POST | `/api/campaigns/{id}/respondents` | Bearer token | Add a respondent ({"email":"…","name":"…","language":"en\|da"}; name and language are optional). 201 with the respondent. Owner or editor only. |
| GET | `/api/campaigns/{id}/respondents` | Bearer token | List respondents, paged (?page=0&size=50, max 200; ?search=; ?status=UNSENT\|SENT\|RESPONDED\|OPTED_OUT\|ALL) |
| POST | `/api/campaigns/{id}/send` | Bearer token | Send the survey to every respondent who has not had it yet: {"sent","failed","blocked","total"}. 409 {"error":"monthly_email_limit_reached","requested","used","limit","resetsOn","sent":0} when the monthly allowance would be exceeded (nothing is sent). |
| GET | `/api/campaigns/{id}/metrics` | Bearer token | NPS, promoters, passives, detractors and response counts for one campaign |
| GET | `/api/campaigns/{id}/activity` | Bearer token | The campaign's activity log (audit entries), newest first |
| GET | `/api/campaigns/{id}/segments` | Bearer token | NPS per segment of one attribute (?attribute=company\|customer_type\|location\|product): value, response count, NPS and whether the sample is big enough (min 5 responses) |
| POST | `/api/campaigns/{id}/simulate` | Bearer token | Test campaigns only: generate simulated responses ({"counts":{"0":3,"10":7},"spreadDays":14,"danishPercent":50}); never sends mail. 400 on a real campaign. |
| POST | `/api/campaigns/{id}/simulate/clear` | Bearer token | Test campaigns only: remove all simulated respondents ({"removedRespondents":n}) |
| POST | `/api/campaigns/{id}/stagger/start` | Bearer token | Test campaigns only: trickle simulated responses into the live feed ({"intervalSeconds":10,"counts":{…}}); returns {"queued":n} |
| POST | `/api/campaigns/{id}/stagger/stop` | Bearer token | Stop a staggered demo and discard what is still queued ({"discarded":n}) |
| GET | `/api/campaigns/{campaignId}/shares` | Bearer token | People the campaign is shared with (owner and anyone it is shared with) |
| POST | `/api/campaigns/{campaignId}/shares` | Bearer token | Share the campaign with an existing Niotio user ({"email":"…","role":"VIEWER\|EDITOR"}, default VIEWER; owner only) |
| DELETE | `/api/campaigns/{campaignId}/shares/{shareId}` | Bearer token | Remove a share (the owner, or the person it was shared with to leave) |
| GET | `/api/metrics` | Bearer token | Get overall metrics (real campaigns included in the score; TEST campaigns are excluded, like the dashboard) |
| GET | `/api/search` | Bearer token | Search campaigns, respondents, comments and cases you can reach (?q=…, at most 20 hits per group); the same results as the command palette |
| GET | `/api/v1/usage/email` | Bearer token | Get survey email usage this month |
| POST | `/api/responses` | Respondent token | Submit response (410 campaign_not_open if the campaign is in the trash) |
| GET | `/api/cases` | Bearer token | The follow-up case inbox across every campaign you can reach (?status=OPEN\|NEW\|IN_PROGRESS\|RESOLVED\|NOT_POSSIBLE\|ALL, ?assignee=MINE\|ALL\|UNASSIGNED, ?overdue=true, ?campaignId=). When follow-up cases are off (plan or campaign switch), this returns 200 with an empty list, not 403. |
| GET | `/api/cases/counts` | Bearer token | Open, overdue, mine and unassigned case counts. When follow-up cases are off, this returns 200 with zeros, not 403. |
| GET | `/api/cases/{id}` | Bearer token | One case: respondent, rating, comment, assignee, status, outcome, due date |
| GET | `/api/cases/{id}/notes` | Bearer token | A case's internal notes, oldest first |
| POST | `/api/cases/{id}/notes` | Bearer token | Append an internal note ({"body":"..."}, max 2000 characters). 403 {"error":"followup_cases_disabled"} when the campaign has cases switched off. |
| POST | `/api/cases/{id}/assign` | Bearer token | Assign ({"assigneeId":7}) or unassign ({"assigneeId":null}) — the assignee is notified. An empty body ({}) is 400; only an explicit null unassigns. 403 {"error":"followup_cases_disabled"} when the campaign has cases switched off. |
| POST | `/api/cases/{id}/status` | Bearer token | Change status ({"status":"RESOLVED","outcome":"RETAINED"}); closing stores the outcome. 403 {"error":"followup_cases_disabled"} when the campaign has cases switched off. |
| GET | `/api/comment-tags` | Bearer token | Your account's comment tag vocabulary with counts, a 30-day trend, a reliable flag (false = too little data) and up to three quoted source comments. Tags are added by hand, or proposed by the browser's built-in AI and then accepted by a person; each tag carries a `source` of HUMAN or AI and an `aiCount`, so the two can be told apart. Filter with ?q= (name contains) and ?source=HUMAN\|AI. |
| POST | `/api/comment-tags` | Bearer token | Create a comment tag. {"name":"Pris","color":"#6c757d"} — name is 1-40 characters and unique per account, case-insensitively. 400 when invalid or already used. |
| PUT | `/api/comment-tags/{id}` | Bearer token | Rename and/or recolour a tag. {"name":"Pricing","color":"#0d6efd"}; existing tag assignments follow the rename. |
| DELETE | `/api/comment-tags/{id}` | Bearer token | Delete a tag and remove it from every comment that carried it. |
| GET | `/api/comments/{responseId}/tags` | Bearer token | Tags on one comment (your account's tags only). Each tag carries a `source` of HUMAN or AI: who applied it to this comment, so an AI-applied tag is visible without a second lookup. |
| PUT | `/api/comments/{responseId}/tags` | Bearer token | Replace the whole tag set on one comment: {"tagIds":[1,4]}. Empty list clears the tags. Needs editor access to the campaign; a viewer or stranger gets 404. |
| GET | `/api/comments` | Bearer token | Search comments across every campaign you can reach: ?q= free text, ?tag=Name or ?tagId= (not both), ?source=HUMAN\|AI (comments carrying a human- or model-applied tag), ?minRating= and ?maxRating= (0-10), ?categories=promoter,passive,detractor, ?campaignId=, ?dateFrom= and ?dateTo= (YYYY-MM-DD, inclusive), paged with ?page= (0-based) and ?size= (default 50, max 200). Every comment carries its tags[] with each tag's own source. An unknown tag name or a foreign tag id is an empty page, like a campaign you cannot see. |
| POST | `/api/comments/{responseId}/tags/{tagId}` | Bearer token | Add one tag to a comment and keep the rest: POST /api/comments/{responseId}/tags/{tagId}. Returns the comment's resulting tag set. Needs editor access to the campaign; a viewer or stranger gets 404, and tagging twice is a no-op. |
| DELETE | `/api/comments/{responseId}/tags/{tagId}` | Bearer token | Remove one tag from a comment and leave the others: DELETE /api/comments/{responseId}/tags/{tagId}. 204, also when the comment did not carry that tag. Same editor access rule as adding. |
| POST | `/api/comment-tags/ai-apply` | Bearer token | Save a tagging run produced in the user's browser: {"model":"Gemini Nano","browser":"Chrome/148","assignments":[{"responseId":12,"tagIds":[5]}],"newTags":[{"name":"Onboarding","color":"#0d6efd","commentIds":[12,14]}]}. Comments you may no longer edit are skipped and counted in the response; a tag id outside your account is a 404. Saved assignments are marked as AI and never overwrite human ones. |
| DELETE | `/api/comment-tags/ai` | Bearer token | Remove every AI-applied tag assignment for this account, then any AI-created tag left without comments. Human tags and human assignments are untouched. |
| DELETE | `/api/comment-tags/ai/runs/{runId}` | Bearer token | Undo one AI save: remove the tag assignments that run applied, then any AI-created tag left without comments. Human tags, human assignments and other runs are untouched. 404 if the run is not yours. |
| PUT | `/api/comment-tags/translations` | Bearer token | Set a tag's name in other languages: {"tags":[{"tagId":7,"names":{"da":"Priser"},"source":"AI"}]}. `name` stays the base name and is the fallback for any language without an entry; an empty name removes that language. Names must be unique per account within one language, case-insensitively — a clash is 400 and nothing is written; a tag id outside your account is 404. Same as editing the names on a tag in the app. |
| POST | `/api/comments/languages` | Bearer token | Store the language a comment was written in: {"detections":[{"responseId":12,"language":"da","confidence":0.93}]}. Detection normally runs in the browser (on-device); this endpoint only stores the result. An empty language clears a previous detection. Codes are BCP-47 primary subtags ("da", "en"), normalised to lower case; a code that is not 2-3 letters is 400 and writes nothing. Needs editor access to the campaign per comment — comments that are gone or no longer editable are skipped and counted, not an error. `GET /api/comments` returns each comment's detectedLanguage. |

## Examples

```bash
curl "https://niotio.dk/api/campaigns" -H "Authorization: Bearer $NPS_TOKEN"
curl "https://niotio.dk/api/campaigns?test=true" -H "Authorization: Bearer $NPS_TOKEN"
curl "https://niotio.dk/api/campaigns?trash=true" -H "Authorization: Bearer $NPS_TOKEN"
curl -X POST "https://niotio.dk/api/campaigns" -H "Authorization: Bearer $NPS_TOKEN" \
  -H "Content-Type: application/json" -d '{"name":"Q1 NPS","campaignType":"REAL"}'
curl -X PUT "https://niotio.dk/api/campaigns/1" -H "Authorization: Bearer $NPS_TOKEN" \
  -H "Content-Type: application/json" -d '{"name":"Q1 NPS"}'
curl "https://niotio.dk/api/metrics" -H "Authorization: Bearer $NPS_TOKEN"
curl -X POST "https://niotio.dk/api/responses?token=RESPONDENT_TOKEN&rating=10&comment=Great"
# comment tags: search by tag or by who applied it (HUMAN|AI), then add/remove one tag
curl "https://niotio.dk/api/comments?tag=Pris&source=AI&size=50" -H "Authorization: Bearer $NPS_TOKEN"
curl "https://niotio.dk/api/comment-tags?source=AI" -H "Authorization: Bearer $NPS_TOKEN"
curl -X POST "https://niotio.dk/api/comments/431/tags/7" -H "Authorization: Bearer $NPS_TOKEN"
curl -X DELETE "https://niotio.dk/api/comments/431/tags/7" -H "Authorization: Bearer $NPS_TOKEN"
```

A campaign is either a real campaign (real respondents, no simulated data) or a test campaign (simulation only, never sends real mail, excluded from your NPS score). Say so with "campaignType": "REAL" | "TEST" (or the legacy boolean "test": true). The type is fixed at creation; sending a different one to PUT /api/campaigns/ returns 400.

## Email usage

`GET /api/v1/usage/email`: Same count as the monthly quota (Europe/Copenhagen calendar month). Unlimited plans: limit and remaining are null. Free: limit 100. Add ?include=campaigns for a per-campaign breakdown (this month only, test campaigns excluded).

```json
{"plan":"PRO",
 "period":{"start":"2026-10-01","end":"2026-10-31","resetsOn":"2026-11-01","timezone":"Europe/Copenhagen"},
 "emails":{"limit":3000,"used":412,"remaining":2588,"percent":14},
 "campaigns":[{"id":12,"name":"Q4 NPS","used":300}]}
```

## Webhooks

Webhooks are available on Pro and Business. Campaign and case events are POSTed to your own URL and signed with an `X-NPS-Signature` header (`t=<unix time>,s=<Base64 HMAC-SHA256 of "<t>.<raw body>">`). Full guide: https://niotio.dk/webhooks.md

## MCP server

AI agents can drive the same API over the Model Context Protocol at `https://niotio.dk/mcp` (same `Authorization: Bearer <API_TOKEN>`). Full guide: https://niotio.dk/mcp.md


---

# niotio — command line client for the Niotio app

A small, dependency-free Go CLI for the Niotio survey REST API. Built to be driven
by humans *and* coding agents: every command supports `--json`, non-interactive
use is explicit (`--yes`), and exit codes are stable.

## Install

The CLI is served **by the Niotio app itself**, so installing needs no GitHub token
and no Go toolchain (the `stigsen/nps` repo is private):

**Recommended — curl | sh from the app** (checksum-verified prebuilt binary):
```bash
curl -fsSL https://niotio.dk/cli/install.sh | sh
```
The installer detects your OS/arch, verifies the sha256 against the app's
`/cli/manifest.json`, installs to `/usr/local/bin` (or `~/.local/bin`), and
pre-sets the API URL (`niotio config set-url https://niotio.dk`).
Override with `NPS_CLI_BASE_URL`, `NPS_CLI_BINDIR`, or skip the URL preset with
`NPS_CLI_NO_CONFIG=1`.

Published artifacts:
- `GET /cli/manifest.json` — version + artifact list (name/size/sha256)
- `GET /cli/checksums.txt`
- `GET /cli/download/niotio_{linux,darwin}_{amd64,arm64}.tar.gz`

They are produced by `scripts/cli-build.sh` (cross-compiles in a throwaway Go
container) and published to the host dir configured by `nps.cli.dist-dir`.

**Alternative — build from a clone** (needs Go 1.23+, always current):
```bash
git clone https://github.com/stigsen/nps.git
cd nps/cli && go build -o "$HOME/.local/bin/niotio" ./cmd/nps
```

## Release

Artifacts are produced by `scripts/cli-build.sh` — it cross-compiles linux/darwin
× amd64/arm64 in a throwaway Go container and writes the tarballs, `checksums.txt`
and `manifest.json` to `nps.cli.dist-dir` (default `/var/lib/nps/cli-dist`), which
the app serves at `/cli/download`.

Two ways to publish:
- **CI (preferred):** push a tag `cli/v1.2.3` (or run the `cli-publish` workflow
  manually). It builds the artifacts and rsyncs them to the host. Requires repo
  secrets `CLI_DEPLOY_HOST`, `CLI_DEPLOY_USER`, `CLI_DEPLOY_SSH_KEY` (and optional
  `CLI_DEPLOY_PATH`, default `/var/lib/nps/cli-dist`).
- **On the host:** run `scripts/cli-build.sh` (writes straight to the served dir).

End users update with `niotio update` (`--check` to only report). It reads
`/cli/manifest.json` from the configured app, verifies the artifact's sha256 and
atomically replaces the running binary. `niotio doctor` also nudges when a newer
build is available.

## Configure

API tokens are created in the app under **Settings → API tokens** (shown once).

```bash
niotio config set-url   https://niotio.dk --profile prod
niotio config set-token <your-token>                --profile prod
niotio config use prod
niotio doctor          # config → health → auth
```

Config lives at `~/.config/niotio/config.toml`. Overrides (highest first):
`--url/--token` flags, then `NPS_URL`/`NPS_TOKEN`/`NPS_PROFILE` env vars, then
the active profile. Useful for CI/agents that shouldn't touch the config file.

## Global flags

| flag | meaning |
| --- | --- |
| `--json` | machine-readable output (recommended for agents) |
| `--profile <name>` | config profile to use |
| `--url <url>` / `--token <t>` | override the target |
| `--yes`, `-y` | confirm destructive actions non-interactively |
| `--timeout <secs>` | HTTP timeout (default 30s) |
| `-q`, `--quiet`, `--no-color` | output tweaks |

Global flags may appear anywhere: `niotio campaign list --json` works.

## Commands

```
# config / diagnostics
niotio config show | config path | config set-url <url> | config set-token <t> | config use <name>
niotio whoami          # verify token + show target
niotio doctor          # connectivity + auth checks
niotio version

# campaigns
niotio campaign list [--trash]
niotio campaign get <id>
niotio campaign create --name <n> [--description <d>] [--close-on <rfc3339>] [--test]
niotio campaign update <id> [--name ...] [--description ...] ...
niotio campaign delete <id>            # -> trash (needs --yes)
niotio campaign restore <id>
niotio campaign activate <id> | deactivate <id>
niotio campaign send <id>              # needs --yes
niotio campaign metrics <id>
niotio campaign respondents <id> [--page N] [--size N] [--search q] [--status s]
niotio campaign activity <id>
niotio campaign simulate <id> [--count N] [--ratings 9:5,3:2] [--spread-days N] [--danish-percent 0-100]   # test campaigns; --count N = N responses per rating (0-10), e.g. --count 5 = 55 responses
niotio campaign simulate-clear <id>    # needs --yes

# respondents / responses
niotio respondent add <campaignId> --email <e> [--name <n>] [--language en|da]
niotio respondent import <campaignId> --csv <file> [--dry-run]
niotio response submit --respondent-token <t> --rating <0-10> [--comment <c>]
    # `--survey-token` is an alias. Global `--token` is the API token, not the survey token.

# follow-up cases (a low rating can open a case per response)
niotio case list [--status open|new|in_progress|resolved|not_possible|all]
                 [--assignee mine|all|unassigned] [--campaign <id>]
niotio case counts             # open / overdue / mine / unassigned
niotio case show <id>
niotio case notes <id>         # note timeline (system notes are marked)
niotio case note <id> --text "..."
niotio case assign <id> --user <userId> | --unassign
niotio case status <id> <NEW|IN_PROGRESS|RESOLVED|NOT_POSSIBLE> [--outcome RETAINED|LOST|UNKNOWN]
# `niotio cases` is an alias for `niotio case list`

# comment tags (per-account vocabulary; SOURCE tells AI work from human work)
niotio tag list [--q <text>] [--source human|ai]
niotio tag create <name> [--color '#0d6efd']
niotio tag update <id|name> [--name <new>] [--color '#0d6efd']
niotio tag delete <id|name>            # strips it from every comment (needs --yes)
niotio tag add <id|name> --comment <commentId>      # keep the comment's other tags
niotio tag remove <id|name> --comment <commentId>
niotio tag ai-remove                   # drop every AI-applied assignment (needs --yes)
# `niotio tags` is an alias for `niotio tag list`

# comments (search by text, tag, rating, campaign; --ai = tags the model applied)
niotio comment list [--tag <name> | --tag-id <id>] [--ai | --human] [--q <text>]
                    [--rating <0-10>] [--min-rating <n>] [--max-rating <n>]
                    [--campaign <id>] [--from <YYYY-MM-DD>] [--to <YYYY-MM-DD>]
                    [--page <n>] [--size <n>]
niotio comment tags <commentId>         # the tags on one comment, with who applied each
niotio comment set-tags <commentId> <tag...>   # replace the whole set (needs --yes)
# `niotio comments` is an alias for `niotio comment list`

# metrics
niotio metrics        # account-wide NPS

# email usage (monthly quota, Europe/Copenhagen month)
niotio usage                # 412 of 1,000 used, 588 left, resets 1 Nov (6 days)
niotio usage --campaigns    # + per-campaign table (this month only; test campaigns excluded)
niotio usage --json         # GET /api/v1/usage/email shape: {plan, period, emails, campaigns?}
                            # plan values: FREE, START, PRO, BUSINESS, INTERNAL (TEAM became PRO, ENTERPRISE became BUSINESS, #58)
```

## How-to guide

### 1. Get an API token

Open the app → **Settings → API tokens** and create one. The raw value is shown
**once** (only its SHA-256 hash is stored), so copy it now.

### 2. Configure the CLI

```bash
niotio config set-url   https://niotio.dk   # or --profile dev/local
niotio config set-token <your-token>
niotio config show                                    # token is masked
```

This writes `~/.config/niotio/config.toml`. For throwaway/CI use, skip the file and
use env vars instead:

```bash
export NPS_URL=https://niotio.dk
export NPS_TOKEN=<your-token>
```

### 3. Verify

```bash
niotio doctor     # checks: config → URL → token → /health → /api/campaigns auth
niotio whoami     # profile, URL, and whether the token is accepted
```

### 4. Common tasks

```bash
# Look around
niotio campaign list
niotio campaign list --trash
niotio campaign get 12
niotio campaign metrics 12
niotio campaign respondents 12 --size 100 --search jane
niotio campaign activity 12          # audit log
niotio metrics                        # account-wide NPS

# Run a survey
niotio campaign create --name "Q4 NPS" --description "Q4 customers" --test
niotio respondent add 12 --email jane@example.com --name "Jane" --language en
niotio respondent import 12 --csv respondents.csv --dry-run   # validate first
niotio respondent import 12 --csv respondents.csv
niotio campaign activate 12
niotio campaign send 12 --yes

# Simulate a run (testing/demos; test campaigns never email real people)
niotio campaign simulate 12 --count 40   # 40 responses per rating (0-10) = 440 total
niotio campaign simulate 12 --ratings 9:20,10:15,3:5
niotio campaign simulate 12 --count 40 --danish-percent 50   # mixed EN/DA respondents
niotio campaign simulate-clear 12 --yes

# Housekeeping
niotio campaign deactivate 12
niotio campaign delete 12 --yes       # → trash
niotio campaign restore 12
```

The CSV for `respondent import` takes `email,name,language`; a header row is
auto-detected and columns are matched by name, so order doesn't matter.

### Follow-up cases

A low rating can open a follow-up case for one response. `case list` defaults to
the **open cases assigned to you**; widen it with `--assignee all --status all`.

```bash
niotio case list                        # open cases assigned to me
niotio case list --assignee unassigned  # the queue nobody owns yet
niotio case note 7 --text "called the customer; follow up Friday"
niotio case status 7 RESOLVED --outcome RETAINED
```

`case assign 7 --user 3` hands a case to a teammate and `--unassign` returns it
to the unassigned queue. `case counts` prints one counter per line (open,
overdue, mine, unassigned), and every command supports `--json`.

`case list` and `case counts` still return HTTP 200 when the plan or campaign
has follow-up cases turned off — an empty list, or counters at zero. They do
not return 403. Operating on an existing case (`note`, `assign`, `status`)
answers `403 {"error":"followup_cases_disabled"}`, and the CLI reports that
message as-is.

### Comment tags

Tags are per account and can be applied by a person or by the browser's built-in model
(the comment page's AI tagging). `SOURCE` in `tag list` is who created the tag, `AI` in the
list is how many of its comments the model applied, and a tag on a comment carries the same
`source` for whoever put it there — so model work is always separable and removable.

```bash
niotio tag list --source ai             # only tags the model created
niotio tag create Pris --color '#0d6efd'
niotio tag add Pris --comment 431       # keep the comment's other tags
niotio comment tags 431                 # what is on this comment, and who applied it
niotio comment list --tag Pris          # search comments by tag
niotio comment list --ai --max-rating 6 # only AI-tagged detractors
niotio comment set-tags 431 Pris Support --yes   # replace the whole set
niotio tag ai-remove --yes              # drop all AI assignments, keep human work
```

`--tag` takes a name (resolved case-insensitively inside your own vocabulary); `--tag-id`
takes an id. An unknown tag matches nothing rather than everything, and `tag add/remove`
needs editor access to the campaign behind the comment — a viewer gets a 404.

### 5. Scripting with `--json`

```bash
niotio campaign list --json | jq -r '.[] | "\(.id)\t\(.name)\t\(.npsScore)"'

id=$(niotio campaign create --name "agent-$(date +%s)" --test --json | jq -r .id)
niotio campaign simulate "$id" --count 50 --yes --json
niotio campaign metrics "$id" --json | jq '{nps:.npsScore, responses:.totalResponses}'
niotio campaign delete "$id" --yes
```

### 6. Built-in help

The CLI ships the same guide off-line:

```bash
niotio help                 # command list + getting started
niotio help examples        # cookbook (also: niotio examples)
niotio help config          # profiles, precedence, tokens
niotio help agents          # agent-specific guarantees and recipes
niotio help exit-codes      # exit code + JSON error contract
niotio help campaign list   # help for one command
```

The guide/help text is available in **English and Danish**: set `NPS_LANG=da`
(or use a `da_*` locale) for Danish. Command names, flags, JSON output and
errors always stay English, so scripts and agents are unaffected.

### 7. Troubleshooting

| symptom | fix |
| --- | --- |
| `no API URL configured` | run `niotio config set-url <url>` or set `NPS_URL` |
| `no API token configured` | run `niotio config set-token <t>` or set `NPS_TOKEN` |
| `HTTP 401` on any command | token invalid/revoked — regenerate in Settings |
| `refusing … without --yes` | mutating commands need `--yes` when not on a TTY |
| wrong target | check `niotio config show`; remember `--url/--token` > env > profile |

## How-to guide (dansk)

Kort dansk guide — den fulde, opdaterede version får du med `NPS_LANG=da niotio help`.

### 1. Hent et API-token
Åbn appen → **Indstillinger → API-tokens** og opret et. Det rå token vises kun
**én gang** (der gemmes kun en hash), så kopiér det med det samme.

### 2. Konfigurér
```bash
niotio config set-url   https://niotio.dk
niotio config set-token <dit-token>
niotio doctor
```
Til CI/engangsbrug: spring filen over og brug `NPS_URL` + `NPS_TOKEN`.

### 3. Almindelige opgaver
```bash
niotio campaign list                 # kampagner
niotio campaign get 12               # detaljer
niotio campaign metrics 12           # NPS for én kampagne
niotio metrics                        # NPS for hele kontoen
niotio usage                         # undersøgelses-e-mails brugt denne måned
niotio usage --campaigns             # + fordelt på kampagner
niotio campaign create --name "Q4 NPS" --test   # tørløb (sender ingen rigtig mail)
niotio respondent import 12 --csv respondenter.csv --dry-run
niotio campaign activate 12 && niotio campaign send 12 --yes

# simulér et forløb (godt til test/demo)
niotio campaign simulate 12 --count 40
niotio campaign simulate-clear 12 --yes
```

### 4. Scripting
Alle kommandoer understøtter `--json`: `niotio campaign metrics 12 --json`.
Destruktive kommandoer kræver `--yes` uden TTY. Exitkoder: `0` ok, `1` fejl,
`2` brugsfejl.

## Agent usage

```bash
export NPS_URL=https://niotio.dk
export NPS_TOKEN=...

# create a test campaign, seed it, read its NPS, tear it down
ID=$(niotio campaign create --name "agent-$RANDOM" --test --json | jq -r .id)
niotio campaign simulate "$ID" --count 40 --json
niotio campaign metrics "$ID" --json | jq '{nps: .npsScore, responses: .totalResponses}'
niotio campaign simulate-clear "$ID" --yes
niotio campaign delete "$ID" --yes
```

Exit codes: `0` success, `1` runtime/API error, `2` usage error. In `--json`
mode errors are emitted as `{"error": ..., "kind": "api|usage|error"}` on
stderr.

## Related docs

- REST API: https://niotio.dk/api/docs.md
- MCP server for AI agents: https://niotio.dk/mcp.md (same Bearer token as the CLI)

## Development

```bash
cd cli
gofmt -l .          # must be empty
go vet ./...
go build ./cmd/nps
go test ./...
goreleaser release --clean   # from cli/, publishes releases
```

CI (`.github/workflows/cli.yml`) runs gofmt/vet/test/build on changes under
`cli/`.

The CLI is exercised by `scripts/prod_smoke_test.sh` (read-only slice against a
live test campaign), per the repo's new-feature smoke-test contract.


---

# Webhook recipes

This page documents **recipes built on the webhooks that already exist** in the app.
There is no separate integration platform, no rule engine and no new runtime: a recipe is
your own small receiver (or a no-code automation in your helpdesk/BI tool) that consumes our
outbound webhook and — where the flow needs it — calls the existing REST API back.

- Settings live on the **campaign detail page → Settings tab → Webhook** (`Webhook URL`,
  `Enable webhooks`) and the **Signing secret** panel right below it.
- Every campaign has its own URL and its own random signing secret; secrets can be rotated
  there at any time.
- The delivery log (**Webhook Events** on the same tab) shows event, status, HTTP status code
  and the receiver's response body, so you can debug without server access.

The API endpoints used by the recipes are listed on `/api/docs`. Authenticate API calls with
`Authorization: Bearer <API_TOKEN>` (create tokens in **Settings → API tokens**).
Webhook callbacks carry **no** API token: they are authenticated by the signature below.

## The envelope

Every event is a `POST` with `Content-Type: application/json` and these headers:

| Header | Example | Meaning |
| --- | --- | --- |
| `X-NPS-Event` | `response.received` | Same value as `event_type` in the body |
| `X-NPS-Signature` | `t=1760860800,s=K7f…=` | Unix timestamp + Base64 HMAC-SHA256 of `"<t>.<raw body>"` |

Body:

```json
{
  "event_type": "response.received",
  "campaign_id": 42,
  "timestamp": "2026-10-19T07:12:33.481Z",
  "test": false,
  "data": { }
}
```

- `test` is `true` for test campaigns (task #22). Test campaigns fire real webhooks so a
  receiver can be rehearsed end-to-end — check this flag before creating tickets or sending
  customer-facing messages.
- `data` is event-specific; see the reference at the end.
- `timestamp` is when the event was created (ISO-8601, UTC). The signature's `t` is when the
  delivery attempt was made; use it for replay protection.

### Delivery and retries

- 10-second timeout per attempt. Any `2xx` counts as delivered; anything else (including a
  timeout or connection error) is a failure.
- Failed events are retried by a scheduled sweep every 5 minutes, **3 attempts in total**
  (initial attempt plus two retries; the scheduled retry is not before ~5 then ~15 minutes).
- After the last attempt the event is marked `FAILED`. Re-enable/repair the receiver and the
  event can be replayed by hand from your side if needed — the payload is stored in the log.
- Event logs are pruned after 90 days.
- Delivery is at-least-once from your point of view: two attempts can both reach the
  receiver (e.g. your `2xx` response was lost). Deduplicate on `(campaign_id, event_type,
  data)` identity, not on arrival count.

### Verifying the signature

Compute `HMAC-SHA256(secret, "<t>.<raw request body>")`, Base64-encode, compare with `s`
using a constant-time comparison, and reject `t` older than ~5 minutes. Use the **raw** body
bytes (before JSON parsing; re-serialising changes whitespace and breaks the HMAC).

Python (Flask):

```python
import base64, hmac, hashlib, time

def verify(req, secret: str, max_skew: int = 300) -> bool:
    header = req.headers.get("X-NPS-Signature", "")
    parts = dict(p.split("=", 1) for p in header.split(",") if "=" in p)
    t, sig = parts.get("t", ""), parts.get("s", "")
    if not t.isdigit() or abs(time.time() - int(t)) > max_skew:
        return False
    expected = base64.b64encode(
        hmac.new(secret.encode(), f"{t}.".encode() + req.get_data(), hashlib.sha256).digest()
    ).decode()
    return hmac.compare_digest(expected, sig)
```

Node/Express (keep the raw body):

```js
const crypto = require("crypto");

function verify(rawBody, header, secret, maxSkew = 300) {
  const parts = Object.fromEntries(header.split(",").map((p) => p.split("=")));
  const t = Number(parts.t);
  if (!Number.isInteger(t) || Math.abs(Date.now() / 1000 - t) > maxSkew) return false;
  const expected = crypto
    .createHmac("sha256", secret)
    .update(`${parts.t}.`).update(rawBody)
    .digest("base64");
  const a = Buffer.from(expected), b = Buffer.from(parts.s || "");
  return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```

## Recipe 1 — Detractor alert into your helpdesk

**Trigger:** `response.received` with `data.rating <= 6` (detractor).
**Goal:** create a follow-up ticket/case within seconds, with the comment and the campaign
name attached, instead of waiting for someone to open the dashboard.

1. On the campaign detail page → **Settings → Webhook**, set the URL of a small receiver
   (or a helpdesk "incoming webhook" endpoint that accepts JSON) and enable webhooks.
2. Receiver: verify `X-NPS-Signature`, ignore `test: true`, and when the rating is 0–6 create
   a case. Return `2xx` quickly (queue slow work) — the request times out after 10 s.

Sample inbound payload:

```json
{
  "event_type": "response.received",
  "campaign_id": 42,
  "timestamp": "2026-10-19T07:12:33.481Z",
  "test": false,
  "data": {
    "respondent_name": "Ada Lovelace",
    "respondent_email": "ada@example.com",
    "rating": 4,
    "csat_rating": 2,
    "comment": "Onboarding was confusing and nobody answered my email."
  }
}
```

`csat_rating` and `comment` are present only when the respondent supplied them.

## Recipe 2 — Ticket closed → create respondent and send the survey

**Trigger:** your helpdesk fires "ticket closed" (its own webhook/automation).
**Goal:** invite the customer to the NPS survey without a CSV import.

This is the reverse direction: your automation calls the existing NPS REST API. Both calls
need `Authorization: Bearer <API_TOKEN>`; the token's user must own (or edit) the campaign,
and the campaign must not be `CLOSED` or `ANONYMIZED`. A `DRAFT` campaign becomes `ACTIVE`
automatically when the first survey goes out.

```bash
# 1) Add the respondent (name is optional; defaults to the email)
curl -sS -X POST "https://niotio.dk/api/campaigns/42/respondents" \
  -H "Authorization: Bearer $NPS_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"email":"ada@example.com","name":"Ada Lovelace","language":"en"}'

# 2) Send all pending surveys for the campaign
curl -sS -X POST "https://niotio.dk/api/campaigns/42/send" \
  -H "Authorization: Bearer $NPS_API_TOKEN"
```

The send response is `{"sent":1,"failed":0,"total":1}`.

Notes:

- `language` is `en` or `da`; omit it to use the API caller's locale.
- Keep the API token in the automation's secret store, never in the receiver URL.
- If your helpdesk can only send a fixed JSON shape, point it at a 20-line adapter that maps
  `ticket.id`/`customer.email` to the two calls above. No new NPS-side integration is needed.

Sample "ticket closed" input (your side, not an NPS format):

```json
{
  "event": "ticket.closed",
  "ticket": { "id": "ZD-1042", "closed_at": "2026-10-19T06:55:00Z" },
  "customer": { "email": "ada@example.com", "name": "Ada Lovelace", "locale": "en" }
}
```

## Recipe 3 — Sync campaign lifecycle to a team channel or BI job

**Trigger:** `campaign.activated`, `campaign.closed` or `campaign.anonymized`.
**Goal:** the team channel (or warehouse job) learns about lifecycle changes without polling
`GET /api/campaigns`.

Slack and Teams incoming webhooks expect their own shapes (`{"text": …}` / Adaptive Card),
so use a tiny translator, or post the payload as-is to a generic endpoint (Zapier/Make/n8n,
an internal Lambda, …). Return `2xx` only after you have accepted the message, otherwise the
event is retried up to three times and you may post it twice.

```json
{
  "event_type": "campaign.closed",
  "campaign_id": 42,
  "timestamp": "2026-10-19T08:00:00.000Z",
  "test": false,
  "data": { "campaign_name": "Q4 onboarding NPS", "user_id": 7 }
}
```

`campaign.anonymized` additionally carries `comments_deleted` (boolean) and, once the
campaign has follow-up cases, `case_notes_deleted` (count of internal case notes removed) —
a good hook for "purge PII downstream" jobs. `campaign.activated` is the right moment to
start (or resume) any external reminder schedule you keep outside the app.

### Case events (closed-loop follow-up)

Campaigns with follow-up cases emit four more event types through the same envelope, the
same `X-NPS-Signature` and the same retry policy:

| `event_type` | When | `data` fields |
| --- | --- | --- |
| `case.opened` | A detractor (or opted-in passive) response opened a case | `case_id`, `response_id`, `rating`, `status`, `outcome`, `assignee_email`*, `due_at`*, `closed_at`* |
| `case.assigned` | The assignee changed — including unassignment (`assignee_email` is then `null`) | same fields |
| `case.status_changed` | Any status move (`NEW` → `IN_PROGRESS`, reopen, …) | same fields |
| `case.closed` | The case reached `RESOLVED` or `NOT_POSSIBLE` (sent *together with* `case.status_changed`) | same fields |

Case payloads never contain the internal notes — only the facts listed above. Re-saving the
same assignee does not emit an event, and bulk/simulated detractor runs open cases silently
for notifications but still emit `case.opened` so test integrations behave like production.

## Event reference

| `event_type` | When | `data` fields |
| --- | --- | --- |
| `response.received` | A respondent submits a survey | `respondent_name`, `respondent_email`, `rating` (0–10), `csat_rating`*, `comment`* |
| `campaign.activated` | Campaign moved to `ACTIVE` | `campaign_name`, `user_id` |
| `campaign.closed` | Campaign moved to `CLOSED` | `campaign_name`, `user_id` |
| `campaign.anonymized` | Closed campaign anonymised | `campaign_name`, `user_id`, `comments_deleted`, `case_notes_deleted` |
| `case.opened` | A response opened a follow-up case | `case_id`, `response_id`, `rating`, `status`, `outcome`, `assignee_email`*, `due_at`*, `closed_at`* |
| `case.assigned` | Case assignee changed (or cleared) | same as `case.opened` |
| `case.status_changed` | Case status moved | same as `case.opened` |
| `case.closed` | Case closed (also emits `case.status_changed`) | same as `case.opened` |

\* optional. `campaign_id` is always in the envelope, not in `data`.

Out of scope on purpose: inbound webhook *engines*, retry queues you configure, and
third-party iPaaS setup. Recipes are receiver-side code; the app keeps exactly one outbound
webhook per campaign and the documented retry policy above.


---

# Niotio MCP server

> Drive Niotio from any Model Context Protocol client — Claude, ChatGPT connectors, Cursor, n8n, or your own agent runtime.

`https://niotio.dk/mcp` speaks **JSON-RPC 2.0 over HTTP** (the MCP *Streamable HTTP* transport, plain-JSON
responses). It needs nothing but an **API token** — the same token the REST API and the `niotio` CLI
use, created in the web app under **Settings → API tokens**.

Every tool backs onto the same endpoint the REST API exposes (see `/api/docs.md`) and to the same
`niotio` CLI command, so REST, CLI and MCP return identical data and enforce identical rules. The MCP
server adds no behaviour of its own.

## Connect

Header: `Authorization: Bearer <API_TOKEN>`. One endpoint, no session state:

```
POST https://niotio.dk/mcp
Content-Type: application/json
Accept: application/json, text/event-stream
Authorization: Bearer $NPS_TOKEN
```

A client that speaks "remote MCP" (Claude, ChatGPT connectors, most agent frameworks) needs exactly
that URL plus the header. For a desktop client that only launches `stdio` servers, bridge it with
`npx -y mcp-remote`:

```json
{
  "mcpServers": {
    "niotio": {
      "command": "npx",
      "args": ["-y", "mcp-remote", "https://niotio.dk/mcp",
               "--header", "Authorization: Bearer ${NPS_TOKEN}"]
    }
  }
}
```

Cursor (`~/.cursor/mcp.json`) takes the same block. n8n's *MCP Client* node takes the URL and a
Bearer credential.

## Handshake

```bash
# 1. initialize — returns the protocol version, capabilities and instructions for the model
curl -s https://niotio.dk/mcp \
  -H "Authorization: Bearer $NPS_TOKEN" -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"0"}}}'

# 2. list the tools (35 of them, with JSON Schema for each)
curl -s https://niotio.dk/mcp \
  -H "Authorization: Bearer $NPS_TOKEN" -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":2,"method":"tools/list"}'

# 3. call one
curl -s https://niotio.dk/mcp \
  -H "Authorization: Bearer $NPS_TOKEN" -H 'Content-Type: application/json' \
  -d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"campaigns_list","arguments":{"test":true}}}'
```

`initialize` is optional in practice: the server is stateless and answers `tools/call` straight
away, which makes `curl` and scripted smoke checks simple.

## Tool results

A successful call answers:

```json
{"jsonrpc":"2.0","id":3,"result":{
  "content":[{"type":"text","text":"[ {\\"id\\": 42, \\"name\\": \\"Q4 customers\\", …} ]"}],
  "structuredContent": {"result": [ … ]},
  "isError": false}}
```

`content[0].text` is the pretty-printed JSON body the REST endpoint would have returned;
`structuredContent` carries the same data as an object (a list result is wrapped as
`{"result": [...]}`). Failures use the REST error text with the HTTP status prefixed, and set
`isError: true` — for example `404: Campaign not found` or
`409: monthly_email_limit_reached`. Protocol-level mistakes (unknown method, unknown tool,
unparseable body) answer a JSON-RPC `error` with `-32601` / `-32602` / `-32700`.

## Tools

| Tool | Use it for | Arguments |
| --- | --- | --- |
| `campaigns_list` | List the caller's campaigns (real and test). Both types are returned unless `test` filters them. Same data as GET /api/campaigns. | `test`? (boolean) |
| `campaigns_get` | Fetch one campaign by id. Returns the campaign object, or an error when the caller cannot see it. Same as GET /api/campaigns/{id}. | `id` (integer) |
| `campaigns_create` | Create a campaign in DRAFT status. Set `test: true` (or `campaignType: "TEST"`) for a sandbox campaign: test campaigns can be simulated but never send real email. Same as POST /api/campaigns. | `name` (string), `description`? (string), `closeOn`? (string), `test`? (boolean), `campaignType`? (string), `autoAnonymizeEnabled`? (boolean), `autoAnonymizeDays`? (integer) |
| `campaigns_update` | Update name/description/close date/anonymisation settings. Omitted fields are left unchanged (a name-only update does not reset description, close date or auto-anonymize). The campaign type is fixed at creation: repeating the current type is fine, changing it is rejected. Same as PUT /api/campaigns/{id}. | `id` (integer), `name` (string), `description`? (string), `closeOn`? (string), `test`? (boolean), `campaignType`? (string), `autoAnonymizeEnabled`? (boolean), `autoAnonymizeDays`? (integer) |
| `campaigns_trash` | Move a campaign to the trash (soft delete, restorable for the retention window). Same as DELETE /api/campaigns/{id}. | `id` (integer) |
| `campaigns_restore` | Restore a trashed campaign. Same as POST /api/campaigns/{id}/restore. | `id` (integer) |
| `campaigns_activate` | Activate a campaign so it can send surveys. Same as POST /api/campaigns/{id}/activate. | `id` (integer) |
| `campaigns_deactivate` | Deactivate (close) a campaign. Same as POST /api/campaigns/{id}/deactivate. | `id` (integer) |
| `campaigns_send` | Send the campaign's pending survey emails. Returns sent/failed/blocked/total. A monthly email-quota refusal comes back as an error with `error: monthly_email_limit_reached`. Same as POST /api/campaigns/{id}/send. | `id` (integer) |
| `campaigns_metrics` | NPS score, response counts and promoter/passive/detractor breakdown for one campaign. Same as GET /api/campaigns/{id}/metrics. | `id` (integer) |
| `campaigns_respondents` | Paged respondent list for a campaign, optionally filtered by search text and status. Same as GET /api/campaigns/{id}/respondents. | `id` (integer), `page`? (integer), `size`? (integer), `search`? (string), `status`? (string) |
| `campaigns_respondent_add` | Add one respondent (email) to a campaign. Owner or editor only. Same as POST /api/campaigns/{id}/respondents. | `id` (integer), `email` (string), `name`? (string), `language`? (string) |
| `campaigns_activity` | The campaign's audit log (who did what, when). Same as GET /api/campaigns/{id}/activity. | `id` (integer) |
| `campaigns_simulate` | Generate simulated responses on a TEST campaign: `counts` maps rating (0-10) to how many responses to create, `spreadDays` backdates them, `danishPercent` sets how many get Danish comments. Same as POST /api/campaigns/{id}/simulate. | `id` (integer), `counts`? (object), `spreadDays`? (integer), `danishPercent`? (integer) |
| `campaigns_simulate_clear` | Remove the simulated data from a test campaign. Same as POST /api/campaigns/{id}/simulate/clear. | `id` (integer) |
| `metrics_overall` | Aggregate NPS metrics across the caller's real campaigns that are included in the score. TEST campaigns are excluded, matching the dashboard and GET /api/metrics. | — |
| `usage_email` | Survey-email usage this month against the plan allowance and when it resets. Add `include: "campaigns"` for the per-campaign breakdown. Same as GET /api/v1/usage/email. | `include`? (string) |
| `responses_submit` | Submit a response using the respondent's survey token (from the survey link). Like every MCP tool, this still needs Authorization: Bearer <API_TOKEN> on /mcp — the survey token identifies the respondent, it does not replace the API token. A respondent whose campaign is in the trash is 410 campaign_not_open (kind api, status 410). Same as POST /api/responses. | `token` (string), `rating` (integer), `comment`? (string) |
| `cases_list` | The follow-up case inbox, across every campaign the caller can reach: detractor responses open a case, and someone has to work it. Filter by status (OPEN by default, or a status name, or ALL), by assignee (MINE default, ALL, UNASSIGNED) and by campaign. Same as GET /api/cases. | `status`? (string), `assignee`? (string), `campaignId`? (integer), `overdue`? (boolean) |
| `cases_counts` | Open / overdue / mine / unassigned counts for the inbox header. Same as GET /api/cases/counts. | — |
| `cases_get` | One case with the respondent, rating, comment, assignee, status, outcome and due date. Same as GET /api/cases/{id}. | `id` (integer) |
| `cases_notes` | The case's internal notes (never shown to the respondent), oldest first. Same as GET /api/cases/{id}/notes. | `id` (integer) |
| `cases_note_add` | Append an internal note to a case (max 2000 characters) — what was agreed with the customer, who you talked to. Same as POST /api/cases/{id}/notes. | `id` (integer), `body` (string) |
| `cases_assign` | Give the case to a user who has access to its campaign (they get notified), or unassign it with `unassign: true`. Same as POST /api/cases/{id}/assign. | `id` (integer), `assigneeId`? (integer), `unassign`? (boolean) |
| `cases_status` | Set the status (NEW, IN_PROGRESS, RESOLVED, NOT_POSSIBLE); closing also records the outcome (RETAINED, LOST, UNKNOWN) and reopening clears the close date. Same as POST /api/cases/{id}/status. | `id` (integer), `status` (string), `outcome`? (string) |
| `comment_tags_list` | The account's comment tag vocabulary with counts, a 30-day trend and a `reliable` flag (false = too little data). Filter with `q` (name contains) and `source` (HUMAN = a person created it, AI = the browser's model created it). Each tag reports its own `source` and an `aiCount` (assignments the model applied), which is how AI tags are told apart. Same as GET /api/comment-tags. | `q`? (string), `source`? (string) |
| `comment_tags_create` | Create a tag in the account's vocabulary. The name is 1-40 characters and unique per account, case-insensitively; a clash is an error. The colour is a hex value like #0d6efd and defaults to grey. Same as POST /api/comment-tags. | `name` (string), `color`? (string) |
| `comment_tags_update` | Rename and/or recolour one tag; omitted fields are left unchanged and every existing assignment follows a rename. Same as PUT /api/comment-tags/{id}. | `id` (integer), `name`? (string), `color`? (string) |
| `comment_tags_delete` | Delete a tag and remove it from every comment that carried it. This is not restorable — confirm with the user first. Same as DELETE /api/comment-tags/{id}. | `id` (integer) |
| `comment_tags_ai_remove` | Remove every tag assignment the model applied for this account, then any AI-created tag left with no comments. Human tags and human assignments are untouched. Same as DELETE /api/comment-tags/ai. | — |
| `comments_search` | Search comments across every campaign the caller can reach. Filter by `q` (text in the comment), `tag` (tag name) or `tagId` (not both), `source` (HUMAN/AI: comments carrying a human- or model-applied tag), rating range, category, campaign and date range. Paged with `page`/`size`. Every comment carries its `tags[]` with each tag's own `source`. Same as GET /api/comments. | `q`? (string), `tag`? (string), `tagId`? (integer), `source`? (string), `minRating`? (integer), `maxRating`? (integer), `categories`? (string), `campaignId`? (integer), `dateFrom`? (string), `dateTo`? (string), `page`? (integer), `size`? (integer) |
| `comments_tags_get` | The tags on one comment, each with its `source` (who applied it). Reading needs access to the campaign; a stranger gets 404. Same as GET /api/comments/{responseId}/tags. | `responseId` (integer) |
| `comments_tags_set` | Replace the whole tag set on one comment: `tagIds` is the complete set, so an empty array clears every tag. Needs editor access to the campaign; a viewer or stranger gets 404 and a tag id outside the account is a 404. Same as PUT /api/comments/{responseId}/tags. | `responseId` (integer), `tagIds` (array) |
| `comments_tags_add` | Add one tag to a comment and keep the tags it already has. Needs editor access; tagging the same tag twice is a no-op. Returns the comment's resulting tags. Same as POST /api/comments/{responseId}/tags/{tagId}. | `responseId` (integer), `tagId` (integer) |
| `comments_tags_remove` | Remove one tag from a comment and leave its other tags. Removing a tag the comment does not carry is a no-op. Same as DELETE /api/comments/{responseId}/tags/{tagId}. | `responseId` (integer), `tagId` (integer) |


## Limits and safety

| Guard | Behaviour |
| --- | --- |
| Rate limit | **120 calls/min per API token**. Above that: HTTP `429` + `Retry-After`, and a JSON-RPC error `-32000` in the body. Every answer carries `X-RateLimit-Limit` / `-Remaining` / `-Reset`. |
| Request size | 64 KB per request, at most 50 messages per batch (`413` / `-32600`). |
| Caching | Every answer is `Cache-Control: no-store` — tool results contain customer data. |
| Audit | Each `tools/call` is logged with token owner, tool, outcome and duration. Argument *values* are never logged (they contain respondent emails and comments). Metrics: `mcp.tool.calls`, `mcp.tool.duration`. |
| Safety hints | Every tool in `tools/list` carries `readOnlyHint`, plus `destructiveHint` for the calls that delete or send (`campaigns_trash`, `campaigns_send`, `comment_tags_delete`, `comment_tags_ai_remove`, …) and `openWorldHint` for the ones that reach real inboxes. A client can use them to ask the user before the calls that change data. |
| Errors | No stack traces or SQL leak out: an unexpected failure answers the REST handler's generic message. |

## Rules that also apply here

- **Comment tags are part of the API.** `comment_tags_*` manage the vocabulary (`list` with
  `q`/`source`, `create`, `update`, `delete`), `comments_search` searches comments by text, tag,
  rating, campaign and date, and `comments_tags_get`/`_add`/`_remove`/`_set` work on one comment.
  Every tag reports a `source` of `HUMAN` or `AI` — on the vocabulary it is who *created* the tag,
  on a comment it is who *applied* it — plus an `aiCount` per tag, so model work is always
  separable from the team's own and can be removed in bulk with `comment_tags_ai_remove`.

- **Tag names exist in several languages (V68).** A tag carries `name` (the base name, the
  model writes English) and `names` — `{locale: name}`, e.g. `{"da":"Priser"}` — filled by the
  page's on-device translator. The base name is the fallback for any language without an
  entry, and a tag can be found by any of its names (`comments_search` with `tag`).
  `PUT /api/comment-tags/translations` sets them in one request; two tags may not share a
  name within one language.

- **A comment carries its own language (V68).** `detectedLanguage` is the language the
  comment was WRITTEN in (a lower-case BCP-47 primary subtag), which is not
  `respondent.language` (the language the survey was sent in). The review page detects it
  on the device and stores it with `POST /api/comments/languages`; `comments_search`
  returns it on every comment.

- **One token, one account.** Every tool acts as the token's owner; there is no cross-account access
  and no way to reach another user's campaign.
- **Test campaigns are a sandbox.** `campaigns_create` with `test: true` (or
  `campaignType: "TEST"`) never sends real email; `campaigns_simulate` only works on them.
- **`campaigns_send` sends real email** to real respondents, and the monthly email quota applies —
  a refusal comes back as `409: monthly_email_limit_reached` with the numbers in the REST body.
  `campaigns_trash` is a soft delete (restorable), so it is safe to retry.
- **Same auth rules as the API.** A missing, invalid or revoked token is `401` with a JSON body;
  a token that lacks access to a campaign is `404`, never a leaked 403.
- The API token is shown once, at creation. Revoke it in Settings → API tokens to cut an agent off
  immediately — the MCP endpoint re-checks it on every request.
