# 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.
