---
title: "MCP Server"
description: "Configure and use the Formbricks v3 Surveys, Creatives and Workflows MCP server"
icon: "robot"
---

For customer connection instructions and API-key fallback, use [MCP setup](/platform/mcp/setup). This handbook describes implementation and contributor behavior.

## Overview

The Formbricks MCP server exposes v3 Surveys, Creatives and Workflows tool surfaces for AI agents. It runs inside
the Formbricks web app at `/api/mcp` and reuses the same v3 API authentication, authorization,
rate limiting, response handling, and audit logging paths as the REST routes.

<Note>
  OAuth 2.1 is the preferred authentication path for MCP clients. Formbricks API keys remain supported as a
  backwards-compatible fallback for local development, self-hosters, and clients that do not support MCP OAuth
  yet.
</Note>

<Note>
  Looking for step-by-step setup guides for Claude Code, the Claude apps, and Codex? See [Connect AI agents
  (MCP)](/platform/mcp/overview). This handbook covers the technical internals.
</Note>

## Endpoint

Use the streamable HTTP MCP endpoint on the Formbricks app:

```text
https://app.formbricks.com/api/mcp
```

For local development:

```text
http://localhost:3000/api/mcp
```

The route supports `POST` requests, runs with the Next.js Node.js runtime, and sets private no-store
response headers. Browser-origin MCP requests must come from the configured Formbricks app origin.

### Protocol revisions

The server implements protocol revision **2026-07-28** and keeps serving the 2025 era from the same
endpoint, so a client on an older revision does not need to change anything. The MCP TypeScript SDK
answers the legacy `initialize` handshake alongside `server/discover`, and `mcp-handler` serves with
`legacy: "stateless"`.

Three parts of the revision are handled by the SDK rather than by our code: the `server/discover` RPC,
the `resultType` field now required on every result, and the `ttlMs` / `cacheScope` cache hints (which
default conservatively to `ttlMs: 0` and `cacheScope: "private"`).

Notable removals in the revision that used to be configured here: protocol-level sessions and the
`Mcp-Session-Id` header, the `initialize` handshake as a precondition, and the HTTP+SSE transport. The
handler therefore takes no `sessionIdGenerator`, `disableSse`, `basePath`, or `maxDuration` option — the
route this handler is mounted on is the only mount point.

OAuth clients discover the protected resource metadata here:

```text
https://app.formbricks.com/.well-known/oauth-protected-resource/api/mcp
```

The metadata advertises `/api/mcp` as the protected resource and points clients to the Better Auth
issuer under `/api/auth`.

## Authentication

### OAuth 2.1

OAuth clients use Authorization Code + PKCE with Dynamic Client Registration. Registration is open
(no initial access token — MCP clients self-register), so it accepts only redirect URIs an attacker
can never receive an authorization code at:

- `http` loopback — `localhost`, `127.0.0.1` or `[::1]` on any port — which local clients (Claude
  Code, Codex, MCP Inspector) use.
- An exact hosted-connector callback: `https://claude.ai/api/mcp/auth_callback`,
  `https://claude.com/api/mcp/auth_callback` and `https://chatgpt.com/connector_platform_oauth_redirect`
  (`HOSTED_MCP_CLIENT_REDIRECT_URIS` in `apps/web/modules/auth/lib/mcp-dcr-redirect-policy.ts`), plus
  any a self-hoster adds with `MCP_DCR_ALLOWED_REDIRECT_URIS`. These match by exact string, so a code
  can only ever reach the vendor.

Any other redirect URI is refused with `400 invalid_redirect_uri` before Better Auth sees the
request. `post_logout_redirect_uris` stays loopback-only. The MCP protected resource is:

```text
https://app.formbricks.com/api/mcp
```

The authorization server issuer is:

```text
https://app.formbricks.com/api/auth
```

Discovery endpoints:

| Endpoint                                           | Purpose                              |
| -------------------------------------------------- | ------------------------------------ |
| `/api/auth/.well-known/oauth-authorization-server` | Better Auth authorization metadata   |
| `/api/auth/.well-known/openid-configuration`       | OpenID Connect metadata              |
| `/.well-known/oauth-authorization-server/api/auth` | RFC 8414 path-insertion alias        |
| `/.well-known/openid-configuration/api/auth`       | RFC 8414 OpenID path-insertion alias |
| `/.well-known/oauth-protected-resource`            | MCP protected resource metadata      |
| `/.well-known/oauth-protected-resource/api/mcp`    | MCP resource-specific metadata       |

Supported scopes:

| Scope                   | Use                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `surveys:read`          | `list_surveys`, `get_survey`, `validate_survey`, `get_workspace_custom_css`, `list_creatives`, `get_creative`, `get_creative_stats`                                                                                                                                                                                                                                                                                   |
| `surveys:write`         | `create_survey`, `generate_survey`, `patch_survey`, `edit_survey_blocks`, `set_survey_block_order`, `delete_survey`, `patch_workspace_custom_css`, `create_creative`, `patch_creative`, `delete_creative`, `duplicate_creative`, `archive_creative`, `restore_creative`                                                                                                                                               |
| `workflows:read`        | `list_workflows`, `get_workflow`, `list_workflow_runs`, `get_workflow_run`, `test_workflow`                                                                                                                                                                                                                                                                                                                           |
| `workflows:write`       | `create_workflow`, `patch_workflow`, `duplicate_workflow`, `delete_workflow`, the enable/disable/archive/unarchive mutations, and the Webhook trigger tools `get_webhook_url`, `regenerate_webhook_url`, `set_sample_payload`, `send_test_request`, `set_expected_response`, and `run_test`                                                                                                                                                                                                                                                                                      |
| `feedbackRecords:read`  | `list_feedback_datasets`, `list_feedback_records`, `count_feedback_records`, `get_feedback_record`, `search_feedback_records`, `find_similar_feedback_records`                                                                                                                                                                                                                                                        |
| `feedbackRecords:write` | `create_feedback_record`, `create_feedback_records`, `update_feedback_record`, `delete_feedback_record`                                                                                                                                                                                                                                                                                                               |
| `responses:read`        | `list_responses`, `count_responses`, `get_response`, `list_tags`                                                                                                                                                                                                                                                                                                                                                      |
| `responses:write`       | `validate_response`, `create_response`, `update_response`, `delete_response`, `batch_delete_responses`, `set_responses_outcome`, `update_tag`, `merge_tags`                                                                                                                                                                                                                                                           |
| `dashboards:read`       | `list_dashboards`, `get_dashboard`, `list_charts`, `get_chart`; with `feedbackRecords:read`, `list_chart_fields`, `get_chart_data`, `list_dashboard_filter_fields`, `list_dashboard_filter_values`, `preview_chart`, `list_chart_field_values` (a Dashboard viewer's token reads `get_chart_data` with a `dashboardId`, `list_dashboard_filter_fields` and `list_dashboard_filter_values` on `dashboards:read` alone) |
| `dashboards:write`      | `create_chart`, `update_chart`, `duplicate_chart`, `create_dashboard`, `remove_chart_from_dashboard`; with `dashboards:read` (Charts: Read, since their answers carry each widget's chart, as `get_dashboard` does), `update_dashboard`, `duplicate_dashboard`, `update_dashboard_layout`, `set_dashboard_filters`, `add_chart_to_dashboard`, `update_widget`                                                         |
| `audience:read`         | `list_contacts`, `list_contact_attribute_keys`, `list_contact_attribute_values`, `list_segments`, `list_action_classes` (read-only family: there is no `audience:write`)                                                                                                                                                                                                                                              |
| `openid`                | OpenID Connect subject interoperability                                                                                                                                                                                                                                                                                                                                                                               |
| `profile`               | User profile claims                                                                                                                                                                                                                                                                                                                                                                                                   |
| `email`                 | User email claim                                                                                                                                                                                                                                                                                                                                                                                                      |
| `offline_access`        | Refresh tokens for MCP clients                                                                                                                                                                                                                                                                                                                                                                                        |

**The rule:** every MCP tool is registered through `registerMcpTool`, which takes the permissions the
tool needs as a mandatory argument and runs the gate before the handler. A permission comes from the
registry in `apps/web/modules/mcp/permissions.ts` (`GLOSSARY.md`, "MCP access") and carries a minimum
access level: read tools declare `read`, every mutating tool declares `write`. Each permission belongs to
a scope family, and the gate maps it to that family's scope at the declared level — Creatives at `read`
needs `surveys:read`, Charts at `write` needs `dashboards:write` — so the table above still says which
scope opens each tool. A tool cannot be registered without a permission: the type refuses an empty list,
and a list that is empty or names a permission or level the registry does not offer throws at
registration. A new tool inherits enforcement by construction — the gate refuses a token whose scopes
don't reach a declared permission before the handler touches a v3 operation, with a 403 that names the
permission, the missing scope and that the client must reconnect. That 403 is in the JSON-RPC tool result,
which is what a client reads; the HTTP `insufficient_scope` challenge comes only from the transport-level
refusal in `modules/mcp/auth.ts`, for a token without any MCP scope. The same gate then holds an OAuth
call to the MCP client's **grant** (ADR-0041): each declared permission must be at least the declared
level in the grant, or the call is refused with a 403 whose detail starts "Not permitted" and names the
permission and level. The grant is read with the user in `modules/mcp/auth.ts`, which refuses a
client without one (that is what makes Revoke immediate), or a token issued under another grant (a
Revoke followed by a new approval): every access token names its grant in an `mcp_grant` claim (`null` when
minted while its user had no grant to the client), set when it is minted (`modules/auth/lib/mcp-grant-token-claim.ts`). API keys have no grant and are gated on scopes
alone. Allow on the consent screen saves the grant; a client registered with `skipConsent` never sees that
screen, so the same claim contributor gives the client one when it exchanges an authorization code, before
the token is minted, by the migration's rule: All access, each permission at its scope family's level,
Tags and Audience at No access. It creates one only when a permission remains after those exclusions (and a
Dashboard viewer's trimming): scopes that give nothing else mint a token without a grant, which `/api/mcp`
refuses, and exchanging again with the same scopes gives the same. A sign-in code issued before a Revoke is refused at the exchange
(`modules/auth/lib/oauth-revocation-marker.ts`), counting a code issued up to `REVOCATION_CLOCK_SKEW_MS` (5 s) after
the mark as issued before it, because the issuing and the revoking pod each stamp by their own clock; the mark a
revocation leaves only ever moves forward,
so two revocations that finish out of order can't lower it. A refresh never creates a grant: the refresh check
refuses a `skipConsent` client without one, as it refuses a consent without one, and refuses a presented
refresh token the mark covers whatever grant stands now, under the user's row: a Revoke that missed a token
rotated meanwhile, then a new approval, can't hand that token's successor the new grant. Every code exchange, for
every client, names its grant (and a `skipConsent` client's creates it) ordered against a Revoke like every
other grant write: the claim takes the user's row `FOR KEY SHARE` and re-reads the mark with the code's issue
time once it has it, because the provider spends the code after the before-hook's check — a Revoke that
lands in between, and an approval after it, leave the token naming no grant rather than the new one. The
code is spent by then, so the claim never fails the exchange: it waits at most 2 s for the row
(`lock_timeout`), and when it can't get the row or read the mark, the token names no grant and `/api/mcp`
refuses it until the client refreshes. A refresh names the grant the user holds, so a client whose grant
stands recovers then; a `skipConsent` client whose grant creation failed too has no grant, is refused at
that refresh, and has to authorize again. Tools that more than one permission
legitimately reaches pass `{ anyOf: [...] }` instead of a plain list, and a tool whose input decides what
it reads passes `{ byInput }`; both keep the tool on the same registration path rather than a hand-rolled
gate.

**How a grant change reaches SpiceDB** (ADR 0042, `modules/mcp/grant-store.ts`). A grant's organization &
workspace access is enforced through SpiceDB relationships, so the order of each write decides what a client
can do in between:

- Narrowing a grant that stays — consent re-approval (`oauth-grant-revocation.ts`) or Authorized apps' Edit
  (`authorized-clients.ts`) — first asks SpiceDB which workspaces the user can select
  (`readMcpGrantReadableWorkspaceIds`), before its transaction takes any lock. Then it locks the grant row
  (`lockMcpGrant`), resolves the chosen access by the shared rule (`resolveMcpGrantSelection`, which re-checks
  the user's memberships from PostgreSQL), and deletes what it takes away from SpiceDB before it commits
  (`narrowMcpGrantAccess`), as the last step before the grant write: nothing that can still refuse the save
  runs after it. Edit checks the cap first; the consent hook resolves the access before it locks the consent
  rows and applies the delete only after its cap check (`resolveMcpGrantNarrowing`,
  `applyMcpGrantNarrowing`), because a refusal after the delete would commit unchanged rows over
  relationships that no longer match them. Right before that delete, it queues the grant's repair in a write
  of its own that commits whatever the transaction does (`deleteMcpGrantRelationshipsBeforeCommit`): the
  grant write after the delete can still fail, and a rollback discards the event its trigger queued, as does
  a process that exits before the commit. Delivered, the repair reconciles under the grant's row `FOR SHARE`,
  so it waits for the transaction and applies whichever rows committed; a failed save also reconciles at
  once, best-effort (`repairMcpGrantsAfterFailedSave`). If SpiceDB can't apply the
  delete, the request fails and the grant is unchanged: Edit answers 500 and the consent screen shows an
  error, both `mcp_grant_not_saved`; a selection the user can't make answers 422
  (`mcp_grant_selection_unavailable`) on both. A grant the client's scopes leave nothing of answers 400
  `mcp_grant_beyond_scopes` on consent: it would connect a client that can do nothing (spec story 17).
  Dependencies (`MCP_PERMISSION_DEPENDENCIES` in `permissions.ts`) are hints, not a save rule (spec story
  16): a grant of Charts without Feedback records saves, and the chart tools answer "not permitted" naming
  what they need. A grant the request can't read at all — unknown field or permission, a level the
  permission doesn't offer, an empty selection — answers 400 `mcp_grant_invalid`. A selection holds at most
  `MAX_MCP_GRANT_SELECTIONS` (100), the `/api/auth` per-list bound (`AUTH_REQUEST_MAX_ENTRIES`), because the
  consent screen sends it in the request body; both screens hold Allow and Save back past it with a hint
  naming the limit, and Edit's route bounds the lists in its schema. Both screens translate the code
  (`getGrantErrorMessage`), never the server's English detail. Edit closes and refreshes on a refusal that
  means it opened on something since changed (`mcp_grant_changed`, `mcp_grant_beyond_scopes`,
  `mcp_grant_selection_unavailable`), and it opens on the stored grant held to the client's current cap,
  so a grant saved before the scopes narrowed can still be edited (`openMcpGrantEdit`).
- A consent approval whose grant can't be saved changes nothing, the consent included. Better Auth writes the
  consent before the hook that saves the grant runs, outside any transaction the hook can join, so a
  before-hook snapshots the client's consent rows (`snapshotConsentBeforeApprovalHandler`) and a failed save
  puts them back: in the grant's transaction for a 422, in a transaction of its own after a 500. That restore
  is best-effort: should it fail too, the consent stays as the provider wrote it, so a later authorization may
  skip the consent screen until the refresh check removes the consent that has no grant.
- What a save adds is written after the commit, best-effort (`projectMcpGrants`).
- Deleting a grant — Revoke, member removal, the switch to Dashboard viewer, the retention sweep, SSO
  recovery — commits first. The missing row already makes `/api/mcp` answer 401, so the relationships are
  removed after the commit, best-effort (`removeDeletedMcpGrants`, `finishRevokedMcpGrants`).
- The outbox event the rows' triggers queued is the repair for every best-effort write. The reconciler
  reads each grant `FOR SHARE` and writes SpiceDB while it holds the row, each write with a gRPC deadline 5 s
  short of its transaction's timeout (`MCP_GRANT_PROJECTION_WRITE_MARGIN_MS`); a write that misses it keeps the
  row through those 5 s before the pass fails. So a reconcile can't put back what a narrowing just removed,
  short of a SpiceDB commit slower than the margin, which the narrowing's own reconcile after its commit
  repairs (ADR 0042).

Every path that locks both a grant row and consent rows takes the grant first. Paths that only need the
grant to hold still while they read the consent (the refresh check, restoring a consent after a failed
approval) lock it `FOR SHARE` (`shareLockMcpGrant`).

A revocation takes the user's row `FOR UPDATE` (`lockUserForMcpRevocation`) before it deletes, the waiting
side of the `FOR KEY SHARE` a grant writer holds (`lockUserForMcpGrantWrite`): a grant written after the
revocation's mark waits there, reads the mark, and doesn't write; one written before is deleted with the
rest. That matters because a revocation writes its mark before its transaction, so the mark can be visible
before the delete runs.

Ending a user's grants from a membership change sits under two earlier locks, so the full order is: the
organization's owner memberships (`runOwnerGuardedTransaction`), then the user's row (`lockUserActiveState`),
then the grant rows, then the consent rows. A member removal and an owner's demotion take all four in that
order, in one transaction. The retention members sweep takes the owners and the user's row to deactivate the
member, commits, and then takes the grant and consent rows in a separate transaction (`revokeCredentials`).
A consent approval creates the grant row, whose foreign key locks the user's row, so it takes that row
`FOR KEY SHARE` first, before the grant: taken at the insert instead, it would close a cycle with a removal
that holds the user's row and waits on the consent rows.

An approval holds the user's row `FOR KEY SHARE` across its SpiceDB narrowing call, so a path that locks the
row `FOR UPDATE` (PATCH users, Reactivate, the sweep's deactivation) can wait up to
`MCP_GRANT_SAVE_TRANSACTION_TIMEOUT_MS` for it.

**There are no exceptions, and tests are what keep it that way.** The feedback-record tools were one
for a while — they gated inside their own handler factories and registered through
`server.registerTool` directly, which meant every handler was checked but a _new_ tool added outside
those factories would have registered unguarded. ENG-2119 moved all ten onto the shared registration
function (`registerMcpTool` today) and
made `guardMcpScopes` / `guardMcpAnyScope` private again, so the guards are no longer reachable from a
tool module.

Be precise about what that guarantees. Privacy removes the hand-rolled gate, and the compiler stops you
forgetting `registerMcpTool`'s permissions argument — but it cannot stop a module calling
`server.registerTool(...)` directly, because `server` is an argument to every tool module. No type
system reaches that. The checks that do: a test pins `registerMcpTool` as the only export of
`guard-permissions.ts`, `tool-permissions.test.ts` pins every registered tool's permissions and the
scopes they map to (it records `registerMcpTool`'s calls, so a tool registered straight through the fake
server's `registerTool` would not show up there), and `feedback-records.test.ts` drives all ten tools with the opposite scope, which
goes red if a tool is registered unguarded _or_ wired to the wrong scope.

**A new scope is advertised only together with a migration that grants it to existing clients.**
`MCP_RESOURCE_SCOPES` is what the protected-resource metadata and the 401 challenge publish, and a
spec-following client (the MCP SDK takes its scope from exactly those) asks for everything in it. The
provider validates that request against the scopes the client _registered_ with, so advertising a scope
to clients that registered before it existed earns them `invalid_scope`. `responses:read` /
`responses:write` show the full sequence: added to `MCP_OAUTH_SCOPES` and to the resource's
`allowedScopes` (ENG-2862), then to each registered client's `scopes` by a data migration that mirrors
what the client already holds and skips `skipConsent` clients, and only then to `MCP_RESOURCE_SCOPES`
(ENG-3470). Skip the client migration and every integration registered before the scope existed
breaks at its next sign-in.

**There is no single mandatory baseline scope.** Authentication requires _at least one_ resource scope
(`MCP_RESOURCE_SCOPES`), so a workflows-only or `feedbackRecords:read`-only grant is a legitimate MCP
client. `list_workspaces` — the workspaceId-discovery prerequisite for every resource tool — therefore
gates on any resource read scope rather than one specific one; its result is derived from the caller's
own memberships and key grants, so admitting any read scope exposes nothing extra.

The authorization server supports all of the above, but the MCP protected-resource metadata
(`/.well-known/oauth-protected-resource/api/mcp`) advertises only the resource scopes an MCP client
needs — `surveys:read`, `surveys:write`, `workflows:read`, `workflows:write`, `feedbackRecords:read`,
`feedbackRecords:write`, `responses:read`, `responses:write`, `dashboards:read`, `dashboards:write`,
`audience:read`, and `offline_access`. Clients derive their Dynamic Client Registration scopes
from that list, so `offline_access` must be advertised there for clients to be issued refresh tokens
(`openid`/`profile`/`email` are OIDC scopes the MCP resource does not require).

<Warning>
  Never advertise a new resource scope without a data migration that grants it to existing `oauthClient`
  rows. The authorization server validates `/authorize` against the scopes the **client** registered
  with, so a client registered before the change requests the newly advertised scope and is rejected with
  `invalid_scope`. It does not fall back to the scopes it already holds, and re-consenting does not help,
  because the same `client_id` is reused. Ship the migration in the same release as the list change, as
  `responses:*` did (see [A new scope family](#a-new-scope-family)), and nothing breaks: users see one
  consent screen naming the new scopes. If a client is already stuck on `invalid_scope`, it recovers by
  registering again: remove and re-add the MCP server (for example `claude mcp remove <name>`, then
  `claude mcp add …`).
</Warning>

OAuth scopes gate MCP tool categories at the token layer, and the user's grant to the client
(`modules/mcp/grant.ts`, stored by `grant-store.ts`) narrows each permission below them. Actual workspace
access is still evaluated at tool execution through the existing v3 authorization checks for the
signed-in Formbricks user, so scope, grant and workspace role are independent gates — a call must satisfy
all three.

Scope groups are **independent**: a token authenticates as long as it holds at least one resource
scope, so a `feedbackRecords:read`-only grant is valid and simply can't reach the survey tools.
`list_workspaces` is the shared discovery tool and accepts any resource read scope.

### API-key fallback

API-key MCP access remains supported. Authenticate with a Formbricks API key in a request header:

```http
Authorization: Bearer fbk_...
```

or:

```http
x-api-key: fbk_...
```

Do not pass credentials in the query string. The MCP route rejects query credential names such as
`api_key`, `x-api-key`, `access_token`, `token`, and `authorization` case-insensitively.

API key permissions are enforced through the same workspace access checks as the v3 REST API:

| Tool                                                                                                                                                                                                        | Minimum Workspace Permission                                                                                                                                                  |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `list_responses`                                                                                                                                                                                            | `read`                                                                                                                                                                        |
| `count_responses`                                                                                                                                                                                           | `read`                                                                                                                                                                        |
| `get_response`                                                                                                                                                                                              | `read`                                                                                                                                                                        |
| `validate_response`                                                                                                                                                                                         | `write` or `manage` — a dry run, but it resolves the same references the write does                                                                                           |
| `create_response`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `update_response`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `delete_response`                                                                                                                                                                                           | `manage`                                                                                                                                                                      |
| `batch_delete_responses`                                                                                                                                                                                    | `manage`                                                                                                                                                                      |
| `set_responses_outcome`                                                                                                                                                                                     | `write` or `manage`                                                                                                                                                           |
| `list_tags`, `update_tag`, `merge_tags`                                                                                                                                                                     | not available: `/api/v3/tags` is session-only, so the tag tools refuse API keys and answer only OAuth callers                                                                 |
| `list_surveys`                                                                                                                                                                                              | `read`                                                                                                                                                                        |
| `get_survey`                                                                                                                                                                                                | `read`                                                                                                                                                                        |
| `create_survey`                                                                                                                                                                                             | `write` or `manage`                                                                                                                                                           |
| `generate_survey`                                                                                                                                                                                           | `write` or `manage` — saves nothing, but spends the organization's AI budget                                                                                                  |
| `validate_survey`                                                                                                                                                                                           | `read` — a dry run; it validates a create or patch payload without writing                                                                                                    |
| `patch_survey`                                                                                                                                                                                              | `write` or `manage`                                                                                                                                                           |
| `edit_survey_blocks`                                                                                                                                                                                        | `write` or `manage`                                                                                                                                                           |
| `set_survey_block_order`                                                                                                                                                                                    | `write` or `manage`                                                                                                                                                           |
| `delete_survey`                                                                                                                                                                                             | `write` or `manage`                                                                                                                                                           |
| `get_workspace_custom_css`                                                                                                                                                                                  | `read`                                                                                                                                                                        |
| `patch_workspace_custom_css`                                                                                                                                                                                | `manage` for an API key; an organization owner or manager for an OAuth user — stricter than `surveys:write`                                                                   |
| `list_creatives`                                                                                                                                                                                            | `read`                                                                                                                                                                        |
| `get_creative`                                                                                                                                                                                              | `read`                                                                                                                                                                        |
| `get_creative_stats`                                                                                                                                                                                        | `read`                                                                                                                                                                        |
| `create_creative`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `patch_creative`                                                                                                                                                                                            | `write` or `manage`                                                                                                                                                           |
| `delete_creative`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `duplicate_creative`                                                                                                                                                                                        | `write` or `manage`                                                                                                                                                           |
| `archive_creative`                                                                                                                                                                                          | `write` or `manage`                                                                                                                                                           |
| `restore_creative`                                                                                                                                                                                          | `write` or `manage`                                                                                                                                                           |
| `list_workflows`                                                                                                                                                                                            | `read`                                                                                                                                                                        |
| `get_workflow`                                                                                                                                                                                              | `read`                                                                                                                                                                        |
| `list_workflow_runs`                                                                                                                                                                                        | `read`                                                                                                                                                                        |
| `get_workflow_run`                                                                                                                                                                                          | `read`                                                                                                                                                                        |
| `test_workflow`                                                                                                                                                                                             | `read` — a dry run; it validates the definition and resolves its trigger references, creating no run                                                                          |
| `create_workflow`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `patch_workflow`                                                                                                                                                                                            | `write` or `manage`                                                                                                                                                           |
| `duplicate_workflow`                                                                                                                                                                                        | `write` or `manage`                                                                                                                                                           |
| `delete_workflow`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `enable_workflow`                                                                                                                                                                                           | `write` or `manage`                                                                                                                                                           |
| `disable_workflow`                                                                                                                                                                                          | `write` or `manage`                                                                                                                                                           |
| `archive_workflow`                                                                                                                                                                                          | `write` or `manage`                                                                                                                                                           |
| `unarchive_workflow`                                                                                                                                                                                        | `write` or `manage`                                                                                                                                                           |
| `get_webhook_url`                                                                                                                                                                                           | `write` or `manage` — the Webhook Secret URL is a credential, so reading it needs write access                                                                                |
| `regenerate_webhook_url`                                                                                                                                                                                    | `write` or `manage`                                                                                                                                                           |
| `set_sample_payload`                                                                                                                                                                                        | `write` or `manage`                                                                                                                                                           |
| `send_test_request`                                                                                                                                                                                         | `write` or `manage`                                                                                                                                                           |
| `set_expected_response`                                                                                                                                                                                     | `write` or `manage`                                                                                                                                                           |
| `run_test`                                                                                                                                                                                                  | `write` or `manage`                                                                                                                                                           |
| `list_feedback_datasets`                                                                                                                                                                                    | `read`                                                                                                                                                                        |
| `list_feedback_records`                                                                                                                                                                                     | `read`                                                                                                                                                                        |
| `count_feedback_records`                                                                                                                                                                                    | `read`                                                                                                                                                                        |
| `get_feedback_record`                                                                                                                                                                                       | `read`                                                                                                                                                                        |
| `search_feedback_records`                                                                                                                                                                                   | `read`                                                                                                                                                                        |
| `find_similar_feedback_records`                                                                                                                                                                             | `read`                                                                                                                                                                        |
| `create_feedback_record`                                                                                                                                                                                    | `write` or `manage`                                                                                                                                                           |
| `create_feedback_records`                                                                                                                                                                                   | `write` or `manage`                                                                                                                                                           |
| `update_feedback_record`                                                                                                                                                                                    | `write` or `manage`                                                                                                                                                           |
| `delete_feedback_record`                                                                                                                                                                                    | `manage`                                                                                                                                                                      |
| `list_chart_fields`, `list_charts`, `get_chart`, `list_dashboards`, `get_dashboard`                                                                                                                         | `read`                                                                                                                                                                        |
| `preview_chart`, `get_chart_data`, `list_chart_field_values`                                                                                                                                                | `read`, and read access to the chart's feedback dataset                                                                                                                       |
| `list_dashboard_filter_fields`                                                                                                                                                                              | `read`; a feedback dataset the caller cannot read through the dashboard is left out of the list, and a Dashboard viewer gets only the keys a chart on the dashboard groups by |
| `list_dashboard_filter_values`                                                                                                                                                                              | `read`, and read access to each feedback dataset its charts read                                                                                                              |
| `create_chart`, `duplicate_chart`                                                                                                                                                                           | `write` or `manage`, and write access to the feedback dataset                                                                                                                 |
| `update_chart`, `create_dashboard`, `update_dashboard`, `duplicate_dashboard`, `update_dashboard_layout`, `set_dashboard_filters`, `add_chart_to_dashboard`, `update_widget`, `remove_chart_from_dashboard` | `write` or `manage`                                                                                                                                                           |
| `list_contacts`, `list_contact_attribute_keys`, `list_contact_attribute_values`, `list_segments`, `list_action_classes`                                                                                     | `read`; all but `list_action_classes` also need the Contacts entitlement                                                                                                      |

Synthesized MCP scopes for an API key: every `:read` scope always (`surveys`, `workflows`,
`feedbackRecords`, `responses`, `dashboards`, `audience`); the matching `:write` scopes when the key has `write` or
`manage` on any workspace — so every existing write key can manage charts and dashboards. The scope
gate and the per-workspace access check above are independent — a `:write` tool requires **both** the
`:write` scope on the token and write/manage on the target workspace.

<Warning>
  Store fallback MCP API keys as environment variables or client secrets. Do not commit API keys into MCP
  client config files.
</Warning>

## Local Setup

Start Formbricks and prepare the database:

```bash
pnpm db:up
pnpm db:migrate:dev
pnpm --filter @formbricks/web dev
```

<Note>
  Restart the dev server after changing tool registrations. The MCP server is built once at module scope by
  `createMcpHandler`, so hot reload does not pick up an added, removed or renamed tool — `tools/list` keeps
  serving the previous set until the process restarts.
</Note>

Verify OAuth discovery:

```bash
curl -sS http://localhost:3000/.well-known/oauth-protected-resource/api/mcp
curl -sS http://localhost:3000/.well-known/oauth-authorization-server/api/auth
```

OAuth-capable MCP clients should dynamically register a public client and request `resource` equal to
the MCP URL:

```text
http://localhost:3000/api/mcp
```

Manual Dynamic Client Registration smoke test:

```bash
curl -sS -X POST http://localhost:3000/api/auth/oauth2/register \
  -H "Content-Type: application/json" \
  --data '{
    "client_name": "MCP Inspector",
    "redirect_uris": ["http://127.0.0.1:6274/oauth/callback"],
    "token_endpoint_auth_method": "none",
    "grant_types": ["authorization_code", "refresh_token"],
    "response_types": ["code"],
    "scope": "openid profile email offline_access surveys:read surveys:write workflows:read workflows:write feedbackRecords:read feedbackRecords:write responses:read responses:write dashboards:read dashboards:write"
  }'
```

<Note>
  This passes `scope` explicitly, so it does **not** reproduce a real client's behavior — real MCP clients
  register with the scopes from the protected-resource metadata's `scopes_supported` (`surveys:read
  surveys:write workflows:read workflows:write feedbackRecords:read feedbackRecords:write responses:read
  responses:write dashboards:read dashboards:write offline_access`, built from
  `MCP_PROTECTED_RESOURCE_SCOPES`). Because the authorization server validates the `/authorize` request
  against the client's **registered** scopes, a client that registers with a narrower set than it later
  requests (e.g. it registers surveys-only but requests `offline_access`) is rejected with `invalid_scope`. To
  smoke-test the real path, omit `scope` and let the client adopt the advertised set, or pass exactly what the
  metadata advertises.
</Note>

<Note>
  For the same reason, the `scope` in the MCP endpoint's 401 `WWW-Authenticate` challenge is exactly the
  metadata's `scopes_supported`, not a subset — a client that hits the 401 before fetching the metadata uses
  the challenge string as its registration scope. The two are derived from one constant
  (`MCP_CHALLENGE_SCOPE`) and a test asserts they stay equal; when they diverged, every new client failed its
  first connect with `invalid_scope` and only succeeded on retry.
</Note>

The consent screen is served at `/account/authorize`; Allow saves the MCP client's grant at the levels
the approved scopes give. Users can revoke approved MCP clients from `/account/settings/authorized-apps`,
which deletes the consent and the grant together, so the client's next call is refused.

Integration tests that call `/api/mcp` as a client does use `apps/web/integration/mcp-client.ts`
(`callMcpTool`, with a token from `integration/oauth-flow.ts` `grant()`); see
`modules/mcp/mcp-grants.integration.test.ts`.

For API-key fallback, create an API key in the Formbricks app with access to the target workspace.
Use the least privileged permission needed by the agent workflow.

Verify that the MCP endpoint can list tools:

```bash
export FORMBRICKS_MCP_API_KEY="fbk_..."

curl -sS -X POST http://localhost:3000/api/mcp \
  -H "Accept: application/json, text/event-stream" \
  -H "Content-Type: application/json" \
  -H "Authorization: Bearer $FORMBRICKS_MCP_API_KEY" \
  --data '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}'
```

## Codex Configuration

### OAuth

Add the HTTP MCP server. Include `--oauth-resource` so the OAuth access token is audience-bound to
the MCP resource URL:

```bash
codex mcp add formbricks-local \
  --url http://localhost:3000/api/mcp \
  --oauth-resource http://localhost:3000/api/mcp
```

Authenticate and request the scopes the agent needs:

```bash
codex mcp login formbricks-local \
  --scopes openid,profile,email,offline_access,surveys:read,surveys:write,workflows:read,workflows:write,feedbackRecords:read,feedbackRecords:write
```

For read-only usage, omit the `:write` scopes:

```bash
codex mcp login formbricks-local \
  --scopes openid,profile,email,offline_access,surveys:read,workflows:read,feedbackRecords:read
```

Scope groups are independent — a token needs at least one resource scope, but not all of them. To use
only the feedback-record tools, request `feedbackRecords:read` (plus `feedbackRecords:write` to create)
and omit the survey scopes.

Codex opens the browser to Formbricks, completes Dynamic Client Registration, and stores the OAuth
client and tokens in Codex's credential store. The user approves the requested scopes on the
Formbricks consent screen.

Equivalent Codex config for the server entry:

```toml
[mcp_servers.formbricks-local]
url = "http://localhost:3000/api/mcp"
oauth_resource = "http://localhost:3000/api/mcp"
```

Verify the registration:

```bash
codex mcp list
codex mcp get formbricks-local
```

Then ask Codex to use the configured server:

```text
Use the formbricks-local MCP server to list surveys for workspace clxx1234567890123456789012.
```

### API-key fallback

Store the API key in the shell environment:

```bash
export FORMBRICKS_MCP_API_KEY="fbk_..."
```

For Codex Desktop on macOS, persist the value in the launch environment and restart Codex Desktop:

```bash
launchctl setenv FORMBRICKS_MCP_API_KEY "fbk_..."
```

Register the local MCP server with a bearer-token environment variable:

```bash
codex mcp add formbricks-local-api-key \
  --url http://localhost:3000/api/mcp \
  --bearer-token-env-var FORMBRICKS_MCP_API_KEY
```

## Claude Configuration

### Claude Code

#### OAuth

Add the remote HTTP MCP server:

```bash
claude mcp add --transport http formbricks-local http://localhost:3000/api/mcp
```

Run `/mcp` and authenticate `formbricks-local`. Claude Code discovers the MCP protected-resource
metadata, registers a public client whose scopes are taken from that metadata's `scopes_supported`
(`surveys:read surveys:write workflows:read workflows:write feedbackRecords:read
feedbackRecords:write offline_access`), and launches the browser-based OAuth flow — there is no
scope-entry step. You approve the requested scopes on the Formbricks consent screen. A `:write` tool
requires both the matching `:write` scope on the token and write/manage permission on the target
workspace at execution time (see [Authentication](#authentication)).

Verify it:

```bash
claude mcp list
claude mcp get formbricks-local
```

For project-shared Claude Code configuration, use `.mcp.json` without static credentials:

```json
{
  "mcpServers": {
    "formbricks-local": {
      "type": "http",
      "url": "http://localhost:3000/api/mcp"
    }
  }
}
```

If the installed Claude Code version does not start the OAuth flow for remote HTTP servers, use the
API-key fallback below until that client is updated.

#### API-key fallback

Set the API key:

```bash
export FORMBRICKS_MCP_API_KEY="fbk_..."
```

Add the HTTP MCP server:

```bash
claude mcp add --transport http formbricks-local-api-key http://localhost:3000/api/mcp \
  --header "Authorization: Bearer $FORMBRICKS_MCP_API_KEY"
```

For a project-shared fallback configuration, keep the API key outside git:

```json
{
  "mcpServers": {
    "formbricks-local-api-key": {
      "headers": {
        "Authorization": "Bearer ${FORMBRICKS_MCP_API_KEY}"
      },
      "type": "http",
      "url": "http://localhost:3000/api/mcp"
    }
  }
}
```

Claude Code will fail to parse this fallback config if `FORMBRICKS_MCP_API_KEY` is not set.

### Claude Desktop

If the installed Claude Desktop build supports remote HTTP MCP server entries, add the same server
definition to the Claude Desktop config file and restart Claude Desktop. Prefer the OAuth entry
without headers when supported; use the API-key header entry only as a fallback.

macOS config path:

```text
~/Library/Application Support/Claude/claude_desktop_config.json
```

Example config:

```json
{
  "mcpServers": {
    "formbricks-local": {
      "type": "http",
      "url": "http://localhost:3000/api/mcp"
    }
  }
}
```

Fallback config with an API key:

```json
{
  "mcpServers": {
    "formbricks-local-api-key": {
      "headers": {
        "Authorization": "Bearer ${FORMBRICKS_MCP_API_KEY}"
      },
      "type": "http",
      "url": "http://localhost:3000/api/mcp"
    }
  }
}
```

Set the API key in the Desktop launch environment before opening Claude Desktop when using the
fallback config:

```bash
launchctl setenv FORMBRICKS_MCP_API_KEY "fbk_..."
```

If a Claude Desktop version only supports stdio MCP servers, use Claude Code for the HTTP endpoint or
add a local stdio-to-HTTP bridge.

## Tool Responses

Tool results include both `structuredContent` and a text content item containing the same JSON string.
Successful results mirror the v3 REST response body and add `requestId` for correlation.

Errors are returned as MCP error tool results with a structured v3 problem payload:

```json
{
  "error": {
    "code": "bad_request",
    "detail": "Invalid survey document",
    "invalid_params": [
      {
        "name": "blocks.0.elements.0.headline",
        "reason": "Required"
      }
    ],
    "requestId": "req_...",
    "status": 400,
    "title": "Bad Request"
  }
}
```

### Declared result shapes

The response tools advertise an `outputSchema`, which no other tool does yet. A client can read the
result shape off `tools/list` rather than inferring it from an example, and the SDK checks the
structured result against the same schema it advertised.

One object root with every branch optional, built by `mcpToolOutput`: a tool answers either the
success payload or the error one, which reads like a union — but a union converts to a root-level
`anyOf`, and the SDK then wraps the result for a 2025-era client to keep the wire shape legal. An
object root is identity on both eras, so the same structured payload reaches every client. The cost is
that the schema cannot say "exactly one of these", which is why the error branch is described in full:
a client can still tell the two apart by which key is present.

## Tool Arguments

Every tool input schema is **strict**: an argument a tool does not declare is rejected, not ignored.
The advertised JSON Schema carries `additionalProperties: false`, and the SDK validates the call before
the handler runs, so an undeclared or misspelled key comes back as an input-validation error result and
the underlying v3 operation is never reached.

This matters most on filters. A dropped filter does not narrow, so the pre-strict behaviour ran the
query wider than asked and reported success — `count_feedback_records` with a misspelled `userId`
(the correct key is `user_id`) returned the count for every record in the dataset, which an agent has no
way to tell from a real answer.

Strictness applies at every depth, not just to the outermost object: a misspelled key inside
`filter.status` is rejected the same way a misspelled top-level argument is. This matters because a
dropped nested filter key does not merely lose the key — it leaves the filter object empty, so the query
runs wider than asked.

Two kinds of exception:

- **Free-form by design.** `blocks`, `metadata`, `welcomeCard` and friends on `create_survey`, and the
  `data` payload on `patch_survey` / `validate_survey`, accept any nested shape. They are validated by the
  v3 survey document contract once the call reaches the operation.
- **The workflow `definition`.** Everything below `definition` on `create_workflow` and `patch_workflow`
  is still open, so a misspelled key inside a trigger, node, edge or node `config` is dropped rather than
  rejected. That schema is shared with the v3 Workflows REST API and the workflow builder, so tightening it
  is a v3 API change rather than an MCP one; it is tracked as ENG-2437. Treat a `create_workflow` result as
  confirming only what it echoes back.

<Note>
  A client that adds its own keys to a tool call's `arguments` will be rejected. Nothing in the MCP spec
  invites that, but it is a behaviour change from earlier Formbricks releases, which silently dropped
  such keys.

Two consequences worth knowing. **Read-modify-write needs trimming:** `update_feedback_record` accepts
only the eight mutable fields, so echoing a record straight back from `get_feedback_record` is rejected
— strip the provenance (`source_*`, `field_*`, `submission_id`, `collected_at`) and the derived
sentiment/emotions/translation first. The error names every key to remove. And **`list_workspaces`
takes no arguments at all**, so a client that pads zero-argument calls with a placeholder key will fail
on the one tool every other workspace-scoped tool depends on for its `workspaceId`.

</Note>

Array arguments are bounded. No array in a tool call may hold more than 1 000 items, and all the arrays
in one call together at most 50 000 elements, at any depth; and a call may nest at most 256 levels of
objects and arrays. A call over any of these is refused with a JSON-RPC `-32602` error before its
arguments are parsed. Fields with a tighter bound advertise it as
`maxItems` in the tool's input schema — `create_survey`'s `blocks`, `endings`, `variables`, `startLogic` and
`languages`, `get_survey`'s `lang`, the list filters' `in` arrays, and `create_feedback_records`'
`records`. A request body may be at most 2 MB, whether or not it declares a `Content-Length`.

## Adding a tool

A tool is a thin adapter over a v3 operation: it parses its input, calls the operation with the caller's
authentication, and relays the result. It never queries the database or checks tenancy itself — the
operation owns both — so the MCP surface follows the v3 API rather than growing semantics of its own.

<Steps>
  <Step title="Start from the operation">
    Find or add the operation in `apps/web/app/api/v3/<resource>/lib/operations.ts`, with its REST route and
    OpenAPI entry. Operations **return** a `Response` for every outcome, errors included, and never throw: MCP
    calls them without the route wrapper. Two families differ: workflow tools call the `@formbricks/workflows`
    handlers through `app/api/v3/workflows/lib/context.ts`, and feedback-record tools call operations over the
    Hub service while the REST route proxies straight to the Hub, so they have no one-to-one REST twin.
  </Step>
  <Step title="Declare the input">
    In `tools/schemas.ts` (or `tools/<resource>-schemas.ts`). Use `.strict()` on the object and
    `z.strictObject` on nested ones, `lengthBoundedArray` for arrays, `.describe()` on every field, and
    `.extend()` the v3 body schema rather than restating it. `schemas.test.ts` fails on any structured object
    that is not strict, but only in the modules it spreads into `allExports` — add a new schema module there.
    Never take a tenant id from input.
  </Step>
  <Step title="Declare the output">
    `outputSchema: mcpToolOutput(<v3 resource schema>)`, built from the v3 resource schema and never
    retyped. The SDK validates every successful result against it (error results are skipped), so a schema
    that drifts fails every call that would otherwise have succeeded.
  </Step>
  <Step title="Register it">
    In `tools/<resource>.ts`, through `registerMcpTool` — the only registration path, which runs the
    permission gate before the handler. Reads call the operation directly:

    ```ts
    registerMcpTool(
      server,
      "get_response",
      {
        title: "Get response",
        description: "Read one survey response in full. Operates on responses, not feedback records.",
        inputSchema: ZMcpGetResponseInput,
        outputSchema: ZMcpResponseOutput,
        annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
      },
      [{ permission: "responses", level: "read" }],
      async (input: TMcpGetResponseInput, ctx) => {
        const authInfo = getMcpToolAuthInfo(ctx);
        const requestId = getMcpRequestId(authInfo);
        const response = await getV3Response({
          responseId: input.responseId,
          authentication: getMcpAuthentication(authInfo),
          requestId,
          instance: MCP_API_ROUTE,
        });
        return await responseToMcpToolResult(response, requestId);
      }
    );
    ```

    A mutation differs in two places, and both are needed: `audit: { action, targetType, targetIdArg? }` in
    the config (records a call the gate refused) and `runMcpMutation(ctx, { action, resource }, ({
    authentication, requestId, auditLog }) => operation(...))` in the handler (records the outcome). Declare
    writes at `write`. A dry run is `read` only if it is a pure function of its input
    (`validate_survey`); one that resolves references is `write` (`validate_response`).

    The permissions a tool declares, each with its access level, are how it joins the grant a user sets
    on the consent screen and on Authorized apps (see `GLOSSARY.md`, "MCP access"). Pick them from the
    registry in `modules/mcp/permissions.ts`; a permission the registry lacks is added there, in the
    category it belongs to, never inline. Declare every permission whose data the tool returns, not just
    the one it is named after: chart tools that read chart numbers declare Charts and Feedback records.
    A tool with no declared permission can't be registered.

  </Step>
  <Step title="Test it">
    Next to the tool, in `tools/<resource>.test.ts`: drive the handler with the opposite scope and assert the
    403 detail, and assert the roster of registered names (see `responses.test.ts` and
    `feedback-records.test.ts`). Add the tool to `tools/tool-permissions.test.ts`, which pins the scopes
    every tool's permissions map to. Run `pnpm test`; restart the dev server to see the tool in `tools/list`.
  </Step>
  <Step title="Document it">
    Add its section under [Available Tools](#available-tools), a row in the scope, permission and REST-mapping
    tables on this page, and in the scope table of `platform/mcp/overview.mdx` if it adds a tool to a scope.
  </Step>
</Steps>

### A new scope family

Reusing `<resource>:read` / `<resource>:write` needs nothing more. A new resource family also needs:

1. The scope pair in `MCP_OAUTH_SCOPES` (`modules/auth/lib/oauth-urls.ts`), and a data migration that appends
   it to existing `oauthResource.allowedScopes` rows — `mcp-oauth-resource-seed.test.ts` fails until the
   migration is listed in its `REPAIR_MIGRATIONS`. Without it, on every instance that already upgraded, a
   client asking only for the new scope gets `invalid_scope`, and one asking for it alongside others is
   silently granted less than it asked for. Neither logs.
2. API-key scopes in `getMcpScopes` (`modules/mcp/auth.ts`), the new category and its permissions in the
   permission registry (`modules/mcp/permissions.ts`), which is what the consent screen and Authorized apps
   show, their labels in `grant-editor-labels.ts` plus the en-US strings (then `pnpm i18n`), and the `anyOf`
   list on `list_workspaces`.
3. `registerXTools(server)` in `modules/mcp/server.ts`, before the final `instrumentMcpServerWithTracing`.
4. Last, `MCP_RESOURCE_SCOPES`, which advertises the scope, in the same release as a data migration that
   appends the pair to existing `oauthClient.scopes` rows. Mirror read/write (`:read` only for clients that
   hold a read scope) and skip `skipConsent` clients, as `20261005130000_eng_3470_grant_responses_scopes_to_clients`
   does. Without it, every client registered before the scope existed requests it and gets `invalid_scope`
   at its next sign-in (see [Authentication](#authentication)).

A family whose tools only read goes in `MCP_READ_ONLY_SCOPE_FAMILIES` instead of `MCP_SCOPE_FAMILIES`: it gets
`<family>:read` and no write scope, its permissions offer only No access and Read, and both migrations grant only
the read scope (`audience`, ENG-7151: 20261112130000 and 20261112130001).

### What makes a tool good

- **One tool per operation.** An MCP-only convenience tool is a second surface to document, test and keep in
  step. When an operation's shape costs the agent real tokens or errors, add a better v3 operation instead —
  `edit_survey_blocks` is one (`PATCH /api/v3/surveys/{surveyId}/blocks`), addressing blocks by id rather than
  resending the whole array.
- **Descriptions are paid for on every session.** `tools/list` ships every description and every field
  `.describe()` to the model each time. State what the tool does, its side effects, and when to prefer another
  tool. Spend a long description only where the wrong pick is likely _and_ silent (`list_responses` against
  feedback records); everywhere else use the one-line form.
- **Small pages, cheap counts.** Cap `limit` below the REST maximum (default 20, max 50–100 against 250), keep
  expensive totals opt-in, use opaque cursors, and give list-shaped resources a `count_*` tool so "how many"
  never means paging.
- **Concise by default.** Return the handle for the next call, not the whole resource: `response_format:
"concise"` returns `id` and `updatedAt`, which is the next call's `expectedUpdatedAt`. The projection is
  MCP-only; REST keeps the full resource.
- **Errors that say what to do next.** Relay the v3 problem document unchanged: `invalid_params` names the
  field, a `409` carries `currentUpdatedAt`. Reject unknown keys instead of dropping them.
- **Honest annotations.** `destructiveHint: true` whenever the previous value is unrecoverable from the
  result, including whole-subtree replaces. For an irreversible delete, consider confirming first the way
  `delete_response` does (elicitation, with a `confirm` argument for clients that cannot answer prompts).

## Available Tools

### list_surveys

Lists surveys in one workspace. The tool is read-only and idempotent.

Input:

```json
{
  "cursor": "opaque-cursor-from-previous-response",
  "filter": {
    "name": {
      "contains": "feedback"
    },
    "status": {
      "in": ["draft", "inProgress"]
    },
    "type": {
      "in": ["link"]
    }
  },
  "includeTotalCount": true,
  "limit": 20,
  "sortBy": "updatedAt",
  "workspaceId": "clxx1234567890123456789012"
}
```

Output:

```json
{
  "data": [
    {
      "createdAt": "2026-04-21T10:00:00.000Z",
      "creator": {
        "name": "Ada Lovelace"
      },
      "id": "clsv1234567890123456789012",
      "name": "Product Feedback",
      "responseCount": 0,
      "status": "draft",
      "type": "link",
      "updatedAt": "2026-04-21T11:00:00.000Z",
      "workspaceId": "clxx1234567890123456789012"
    }
  ],
  "meta": {
    "limit": 20,
    "nextCursor": null,
    "totalCount": 1,
    "workspaceSurveyCount": 3
  },
  "requestId": "req_..."
}
```

`totalCount` is the number of surveys matching the filters; `workspaceSurveyCount` is every survey in the
workspace, archived ones included and independent of the filters, so it can be larger. Both are `null`
when `includeTotalCount` is `false`.

### get_survey

Gets one survey by ID. The tool is read-only and idempotent.

An app survey's `targeting` is its segment's filters, which carry literal contact attribute values. Every
survey tool (`list_surveys`, `get_survey`, `create_survey`, `patch_survey`, and the block tools'
`detailed` answer) leaves `targeting` out unless the caller holds Segments and Contact attributes at Read,
as `list_segments` needs. It is left out rather than set to `null`, so a survey sent back to `patch_survey`
as read keeps its targeting. The REST operations return it as before.

Input:

```json
{
  "lang": ["en-US"],
  "surveyId": "clsv1234567890123456789012"
}
```

`lang` is optional. When supplied, it filters translatable survey fields to the requested language
codes or configured aliases.

### create_survey

Creates a block-based link survey using the v3 survey document contract. The tool writes data and is
not idempotent.

A block is `{ name, elements[], id? }`; an element is `{ id, type, headline, ... }`. The element
`type` is one of `fileUpload`, `openText`, `multipleChoiceSingle`, `multipleChoiceMulti`, `nps`,
`cta`, `rating`, `consent`, `pictureSelection`, `cal`, `date`, `matrix`, `address`, `ranking`,
`contactInfo`, `csat`, `ces`, `signature`. Element ids are caller-supplied and become immutable once the survey
leaves draft; block ids are generated when omitted. Translatable fields are keyed by locale code and
must carry every configured language — the internal `default` key is rejected.

Once a survey has left `draft` (active, paused, completed, or scheduled, which is paused until its
publish date), its question codes, answer codes, question types and option text in every language are
locked, and an option, matrix row or column that existed at launch cannot be deleted. The tools refuse
such an edit with `immutable_question_code`, `immutable_answer_code`, `immutable_question_type`,
`immutable_option_text` or `immutable_option_deletion`, naming the field. Adding questions and options is
still allowed, and an agent can unlock a survey by reverting it to `draft`.

Every element except `cta` may carry an optional **question code**, and every choice, matrix row or
column and picture choice an optional **answer code**: `{ "id": "satisfaction", "code": "q1", ... }`
and `{ "id": "c1", "code": "1", "label": { ... } }`. A missing code is not an error. A question code
starts with a lowercase letter, then lowercase letters, digits and `_` (no `__`, no trailing `_`, at
most 30 characters); an answer code uses the same characters, may start with a digit and is at most 20
characters. Neither may be an SPSS reserved word (`all`, `and`, `by`, `eq`, `ge`, `gt`, `le`, `lt`,
`ne`, `not`, `or`, `to`, `with`) or an export column name (`response_id`, `language`, `outcome`, ...).
Question codes are unique across the survey, its Embedded Data names and the other questions' ids,
ignoring case; answer codes are unique within their question, with a matrix's rows and columns checked
separately. A clash is reported as `invalid_params`, and `validate_survey` runs the same check.

The same list is carried on the tool's own `blocks` description, generated from
`TSurveyElementTypeEnum` so the two cannot drift. Per-type required fields are not restated here.
`validate_survey` will reject an element that is missing them, but it reports the element **by its
position** rather than naming the field: the element schema is an undiscriminated union, so a wrong
or absent `type` makes every branch fail and the message is a generic `Invalid input`. Send the
type's own fields with the element rather than expecting the validator to name them.

An optional `startLogic` array holds the **rules before the first question**: the survey runs them as
soon as it loads, before the welcome card and on start-at links. Each rule has the shape of a block's
`logic` rule, but may only `jumpToBlock` (to a block, or to an ending to screen the respondent out),
`calculate` and `markLowQuality`, and may read `hiddenField`, `variable` and `reserved` operands only, since nothing has been
answered yet. Anything else is refused with the exact path, such as `startLogic.0.actions.1`. On
`patch_survey`, `null` or `[]` removes them and an omitted `startLogic` is kept; `get_survey` always
returns the array, `[]` when there are none.

A block rule may also carry a `markLowQuality` action, `{ "id": "<cuid2>", "objective": "markLowQuality" }`
with no target (ENG-6933). When the rule fires, the respondent sees nothing and the response is marked Low
quality as a reviewer would mark it. It is allowed in `startLogic` too (ENG-6952), where the flag rides on
the response's first write, a screen-out's finished response included; `requireAnswer` is refused there.

Input:

```json
{
  "blocks": [
    {
      "elements": [
        {
          "headline": {
            "de-DE": "Was sollen wir verbessern?",
            "en-US": "What should we improve?"
          },
          "id": "satisfaction",
          "required": true,
          "type": "openText"
        }
      ],
      "name": "Main Block"
    }
  ],
  "defaultLanguage": "en-US",
  "endings": [],
  "hiddenFields": {
    "enabled": false
  },
  "languages": [
    {
      "code": "de-DE",
      "enabled": true
    }
  ],
  "metadata": {
    "cx_operation": "enterprise_onboarding",
    "title": {
      "de-DE": "Produktfeedback",
      "en-US": "Product Feedback"
    }
  },
  "name": "Product Feedback Survey",
  "status": "draft",
  "variables": [],
  "welcomeCard": {
    "enabled": true,
    "headline": {
      "de-DE": "Willkommen",
      "en-US": "Welcome"
    }
  },
  "workspaceId": "clxx1234567890123456789012"
}
```

Output uses the same survey resource shape as `GET /api/v3/surveys/{surveyId}` and includes the MCP
`requestId`.

#### Typed Embedded Data

`create_survey`, `patch_survey` and `validate_survey` take the survey's Embedded Data as typed
`embeddedFields` (ADR 0028), next to the legacy `variables` and `hiddenFields`, and `get_survey` returns
both. An entry is `{ storageKey, key, name, source, dataType, defaultValue, locked }`:

- `source: "computed"` is set by logic. Logic operands of type `variable` and calculate actions name its
  `storageKey` (a cuid2, generated when omitted). Its `dataType` is `string`, `number`, `date` or
  `boolean`. A `boolean` (true/false) one is set only by a one-step `assign` of `true`, `false` or another
  `boolean` field, never by an expression.
- `source: "ingested"` arrives by URL parameter or SDK. Operands of type `hiddenField` name its
  `storageKey`, which defaults to its name. Only ingested fields can be `locked`.
- A workspace library field is linked by sending `{ "key": "plan_tier" }` alone: the server fills in the
  library's definition. A key the library does not have is a `400` at `embeddedFields.<i>.key`.

`embeddedFields` is the complete set, and the legacy pair is derived from it. Either format alone works.
Sent together, they have to describe the same fields, or the call fails with a `400` naming each path
where they differ, so an edit made in one format is never silently dropped.

### validate_survey

Validates a create or patch payload without writing survey changes. The tool is read-only and
idempotent; workspace access is still checked when `workspaceId` is present, at `read` level —
matching the `surveys:read` scope the tool declares.

Create validation input:

```json
{
  "data": {
    "blocks": [
      {
        "elements": [
          {
            "headline": {
              "en-US": "What should we improve?"
            },
            "id": "satisfaction",
            "required": true,
            "type": "openText"
          }
        ],
        "name": "Main Block"
      }
    ],
    "defaultLanguage": "en-US",
    "name": "Product Feedback Survey",
    "workspaceId": "clxx1234567890123456789012"
  },
  "operation": "create"
}
```

Patch validation input:

```json
{
  "data": {
    "name": "Updated Product Feedback Survey"
  },
  "operation": "patch",
  "surveyId": "clsv1234567890123456789012"
}
```

Validation failures return `200` with `valid: false` and structured `invalid_params`, matching
`POST /api/v3/surveys/validate`.

Custom CSS validation input — processes CSS alone, for a preview, without saving anything:

```json
{
  "data": {
    "customCss": {
      "dark": null,
      "light": "[data-fb-part=\"headline\"] { font-weight: 600; }"
    }
  },
  "operation": "customCss",
  "scope": "survey",
  "surveyId": "clsv1234567890123456789012",
  "workspaceId": "clxx1234567890123456789012"
}
```

`scope` is `workspace` or `survey`; `surveyId` is optional, survey scope only, and must belong to
`workspaceId`. A valid result carries the compiled `customCss` and `warnings` (removed constructs, each with
a stable `code`, `appearance`, `line`, `column` and `reason`); an invalid one carries `errors` and no compiled
output. A create or patch payload that includes `customCss` is processed the same way, additively.

### generate_survey

Drafts a survey from a plain-language `prompt` with the organization's AI and **saves nothing**: it returns
the draft as a v3 create body (`payload`), the draft's `language`, and `validation`, which says whether
`create_survey` would accept the payload as is. The agent reviews the draft and saves it with
`create_survey`. The input is the `POST /api/v3/surveys/generate` body: `workspaceId`, `prompt` (4 to 1200
characters), `type` (`link` or `app`), and the optional `language` (preferred) and `surveyLanguage`
(required) codes.

It declares Surveys: Write, as the REST route needs `readWrite`, because every call runs a model on the
organization's budget. Both paths go through `generateV3Survey`
(`apps/web/app/api/v3/surveys/generate/operations.ts`), which charges the same 10-per-minute budget
(`v3SurveyGenerate`, per user or API key) and checks the organization's AI toggle, the license entitlement
and the provider configuration. An organization without AI gets the AI error code, never a draft.

```json
{
  "prompt": "Ask new users what slowed them down during onboarding",
  "workspaceId": "clxx1234567890123456789012"
}
```

### patch_survey

Updates a survey by ID using the v3 survey patch contract. The tool writes data, can be
destructive, and is not idempotent. Omitted top-level fields are preserved. Provided top-level
objects and arrays replace that whole subtree, so omitted nested entries inside a provided subtree
can be removed. The patch tool does not deep-merge nested objects and does not implement JSON Patch.
For a change confined to one or a few blocks, prefer `edit_survey_blocks`, which does not require
resending the others.

The full `get_survey` output may be sent straight back: server-owned fields (`id`, `workspaceId`,
`type`, `createdAt`, `archivedAt`, `defaultLanguage`, `languages[].alias`) are accepted and verified,
and changing one is a `422` `read_only_field` rather than a silent ignore. A round-tripped
`updatedAt` acts as an optimistic-concurrency precondition, so the patch is rejected with `409` if
the survey changed since your read.

<Note>
  For agent workflows, fetch the current survey first, modify only the intended top-level fields, run
  `validate_survey` with `operation: "patch"`, and then submit the same patch with `patch_survey`. If the
  change is confined to blocks, stop here and use `edit_survey_blocks` or `set_survey_block_order` instead —
  they are cheaper and cannot drop a block by omission.
</Note>

Input:

```json
{
  "data": {
    "metadata": {
      "cx_operation": "enterprise_onboarding",
      "title": {
        "en-US": "Updated Product Feedback"
      }
    },
    "name": "Updated Product Feedback"
  },
  "surveyId": "clsv1234567890123456789012"
}
```

Output uses the same survey resource shape as `GET /api/v3/surveys/{surveyId}` and includes the MCP
`requestId`.

#### Confirmation on surveys with responses

`patch_survey`, `edit_survey_blocks`, `set_survey_block_order` and `delete_survey` take an optional
`confirm` argument. On a survey that is not a draft and already has at least one response, a call
without `confirm: true` changes nothing: it returns an error (`status: 428`, "Confirmation required")
whose `detail` is the caution the editor shows a person — mixed old and new responses for a change, the
loss of every response for a delete — followed by "Pass confirm: true after the user agrees". The agent
shows that to the user and retries with `confirm: true` only after they agree. Drafts and surveys
without responses need nothing. The rule is MCP-only: the v3 HTTP API is unchanged, and an operation
enforces it only when the tool passes `writeConfirmation`.

`customCss` on `create_survey` and `patch_survey` is source only — `{ "light": "…", "dark": "…" }`, both
keys, each a string or `null`; `null` clears it, and on a patch an omitted `customCss` is kept. Compiled
output is computed by the server, and a payload carrying `compiled` or `processorVersion` is rejected. A
successful write that processed CSS returns the removed constructs as a top-level `warnings` array beside
`data`; adding or editing CSS on a Cloud organization without the Scale plan is a `403`
`custom_css_plan_required`, clearing it never is. `get_survey` returns the source in `customCss`.

### get_workspace_custom_css

Reads a workspace's shared survey CSS: `customCss` and `previous` (the one recoverable revision) as
source, `status` (`ok`, `stale` — recompiled from source because the processor changed — or `withheld`,
when that source no longer passes and respondents get none of it), and `canEdit` / `planAllowed` for the
caller. Read-only and idempotent; `surveys:read` plus read access to the workspace.

Input:

```json
{
  "workspaceId": "clxx1234567890123456789012"
}
```

### patch_workspace_custom_css

Saves or clears the workspace's shared survey CSS. `customCss` replaces both fields; `null` clears all of
it, and unchanged source writes nothing. Removed constructs come back as top-level `warnings`; CSS the
processor rejects is a `422` with `details.errors`, and the saved CSS stays in effect. The replaced value
becomes `previous`, restored by sending its source back.

The scope is `surveys:write` because this is shared survey CSS, but the scope is only the first gate:
the operation still requires an **organization owner or manager** (OAuth or session user) or an API key
with **`manage`** on the workspace — a `write` grant is refused — and, on Cloud, the Scale plan to add or
edit. Both refusals, like a scope refusal, are audited.

Input:

```json
{
  "customCss": {
    "dark": "#fbjs[data-appearance=\"dark\"] { --acme-ink: #e6eef5; }",
    "light": "[data-fb-part=\"button-primary\"] { border-radius: 999px; }"
  },
  "workspaceId": "clxx1234567890123456789012"
}
```

Both tools declare an `outputSchema`: the workspace custom CSS resource under `data`, plus `warnings` on
a write.

### edit_survey_blocks

Edits a survey's blocks in place — update, insert or remove whole blocks without resending the ones
you are not changing. The tool writes data, can be destructive, and is not idempotent. Operations
apply in order against a single snapshot and land atomically: either all of them do or none do.

Blocks are addressed by id, never by position, so a concurrent edit cannot redirect an operation onto
a different block. An `update` replaces the target block entirely, and the replacement must carry
every language the survey has configured. An `insert` anchors at `start`, `end`, or `after` a block
id — including one an earlier operation in the same request inserted. `block.id` is optional on
both: an insert without one gets a server-generated id, returned in the concise response's `applied`
list, and an update takes it from the operation's `id`.

Removing a block orphans any answers already collected for its elements, and the API cannot undo
that. The editor shows a human a caution before this, and the tool does the same: on a survey that is
not a draft and has responses it refuses until the call passes `confirm: true` (see
[Confirmation on surveys with responses](#confirmation-on-surveys-with-responses)).

<Note>
  Fetch the survey first and pass its `updatedAt` as `expectedUpdatedAt`. If the survey changed since your
  read the call returns `409` with both timestamps in `details` — re-read and retry. The concise response
  carries the new `updatedAt`, so a run of edits chains without fetching again.
</Note>

Input:

```json
{
  "expectedUpdatedAt": "2026-04-21T10:00:00.000Z",
  "ops": [
    {
      "block": {
        "elements": [
          {
            "headline": { "en-US": "How satisfied were you?" },
            "id": "satisfaction",
            "inputType": "text",
            "required": true,
            "type": "openText"
          }
        ],
        "id": "k1p9wq2m4x7c3v8b5n6t0j2r",
        "name": "Satisfaction"
      },
      "id": "k1p9wq2m4x7c3v8b5n6t0j2r",
      "op": "update"
    }
  ],
  "response_format": "concise",
  "surveyId": "clsv1234567890123456789012"
}
```

Output defaults to a concise acknowledgement — `id`, `updatedAt`, `blockCount` and the operations
applied — plus the MCP `requestId`. The full survey resource is ~15k tokens on a large survey, which
would refill an agent's context as fast as resending the blocks did, so it is opt-in via
`response_format: "detailed"`. `REST` always returns the full resource.

### set_survey_block_order

Replaces the order of a survey's blocks by listing every current block id exactly once. Block content
is untouched. The tool writes data and can be destructive, but unlike every other survey write it is
**idempotent**: the same order yields the same survey, and an order that already matches performs no
write at all, so `updatedAt` does not move and other callers' preconditions stay valid. A stale
`expectedUpdatedAt` still returns `409` on that path: the precondition is evaluated before the
method, so a no-op outcome never reports success to a caller whose view is out of date.

Because the list must be a permutation, a dropped or duplicated block is rejected rather than
silently applied — the failure that resending the whole `blocks` array cannot catch.

Input:

```json
{
  "expectedUpdatedAt": "2026-04-21T10:00:00.000Z",
  "order": ["b4h8s2d6f0g3j5k7l9z1x3c5", "k1p9wq2m4x7c3v8b5n6t0j2r"],
  "response_format": "concise",
  "surveyId": "clsv1234567890123456789012"
}
```

Output matches `edit_survey_blocks`: concise by default, echoing the applied `order`.

### delete_survey

Deletes one survey by ID. The tool is destructive, writes data, and is not idempotent.

Input:

```json
{
  "surveyId": "clsv1234567890123456789012"
}
```

The v3 REST delete operation returns `204 No Content`. The MCP tool result contains the `requestId`
so callers can correlate the audit trail:

```json
{
  "requestId": "req_..."
}
```

### Creative tools

Nine tools over the v3 Creatives API, one per documented operation but one: `list_creatives`, `get_creative`,
`get_creative_stats`, `create_creative`, `patch_creative`, `delete_creative`, `duplicate_creative`,
`archive_creative` and `restore_creative`. The one operation without a tool is `POST
/api/v3/creatives/pause`, which pauses every creative a survey opens so the survey screens stay within
the rate limit however many there are; an agent pauses one with `patch_creative`. A creative is a
feedback button or banner the web SDK renders
on a customer's site. Each tool is a thin adapter: it maps its input onto the operation in
`app/api/v3/creatives/lib/operations.ts` and relays the answer, so validation, status rules and
authorization are the REST API's, tested once there.

**Scopes.** There is no `creatives:*` scope: reads declare `surveys:read` and writes `surveys:write`, so
any client that can manage surveys can manage creatives and the consent screen offers nothing new (its
`surveys:*` lines now say "surveys and creatives"). Splitting the scope later is additive — add
`creatives:*` and grant it to every client already holding `surveys:*`, as for responses in ENG-3470.
The workspace permission behind the operation is a separate gate, as for every tool.

**`list_creatives`** takes a required `workspaceId`, `limit` (default 20, at most 50), an opaque `cursor`,
`filter.name.contains`, `filter.type.in`, `filter.displayStatus.in`, `surveyId` (creatives whose
Destination is that survey) and `sortBy`. Archived creatives are left out unless
`filter.displayStatus.in` names `archived`. `meta` carries `limit` and `nextCursor` only: the creative
list has no total.

```json
{
  "filter": { "displayStatus": { "in": ["active", "scheduled"] } },
  "workspaceId": "clxx1234567890123456789012"
}
```

**`create_creative`** takes one flat object. `type` (`feedbackButton` or `banner`) selects the shape of
`content` and `styling` and can never change (a union cannot be a tool's root, so the shapes are
advertised side by side); the v3 create body validates the object behind the scenes, so a `content` that
does not fit the `type` is refused before the operation runs. A creative is
created as a draft unless `status` is `inProgress`, which publishes it and so needs its Destination and
default-language text (a `422` names the field). Texts are keyed by locale code.

```json
{
  "content": { "icon": "messageSquare", "label": { "en-US": "Feedback" } },
  "destination": { "surveyId": "clsv1234567890123456789012", "type": "survey" },
  "name": "Pricing page feedback",
  "status": "inProgress",
  "type": "feedbackButton",
  "workspaceId": "clxx1234567890123456789012"
}
```

**`patch_creative`** takes `{ creativeId, data }`. Each group in `data` (`content`, `styling`,
`destination`, `distribution`, `schedule`, or `defaultLanguage` with `languages`) replaces the stored group
as a whole, which is why the tool is `destructiveHint: true`: read the creative with `get_creative` and
send the complete group. Publish, pause, close and reopen by setting `status`. An archived creative is
read-only (`422`): restore it first.

**`delete_creative`** is permanent and takes the creative's counts with it; `archive_creative` takes one
off the site and keeps its history, and `restore_creative` brings it back, always as a draft to publish
again. Archiving and restoring are idempotent; archiving is annotated destructive, like `archive_workflow`:
it takes the creative off the site, and its status doesn't come back with it. Restoring is not. `duplicate_creative` copies a creative into a new draft without
its counts. `get_creative_stats` reads Impressions, Clicks and Click rate per UTC day, with an optional
`from`/`to` range and `groupBy` of `page` or `device`.

There is no `validate_creative` dry run yet.

### Workflow tools

Workflow tools operate on the v3 Workflows API (trigger → condition → action automations). They reuse
the same authentication, authorization, audit logging, and error mapping as the survey tools.

#### list_workflows

Lists workflows in one workspace. Read-only and idempotent.

Input:

```json
{
  "cursor": "opaque-cursor-from-previous-response",
  "filter": {
    "name": { "contains": "welcome" },
    "status": { "in": ["draft", "enabled"] }
  },
  "limit": 20,
  "sortBy": "updatedAt",
  "workspaceId": "clxx1234567890123456789012"
}
```

Output mirrors the v3 list envelope: `{ "data": [...], "meta": { "limit", "nextCursor" }, "requestId" }`.
Omitting `filter.status.in` returns every status except archived. Each workflow's embedded `lastRun.error`
is `null` without Responses: Read, as on `get_workflow`.

#### get_workflow

Gets one workflow by ID. Read-only and idempotent. Unknown or cross-workspace ids return `403`
(never `404`) so existence is not leaked. Each workflow carries its `lastRun` summary, whose `error` can
quote what a failed step sent; without Responses: Read (in the grant and in the token's scopes) it comes
back as `null`, on this tool, on `list_workflows`, and on every workflow mutation that returns the resource
(`patch_workflow`, `enable_workflow`, and the rest).

```json
{ "workflowId": "clwf1234567890123456789012" }
```

#### list_workflow_runs

Lists workflow runs for a workspace, newest first. Read-only and idempotent. Declares Workflow runs: Read
alone, like `get_workflow_run`, and like it leaves out what can quote respondents' answers: without
Responses: Read (in the grant and in the token's scopes) each run's `error` comes back as `null`.

```json
{
  "filter": { "isDryRun": false, "status": { "in": ["completed"] } },
  "limit": 20,
  "responseId": "clrs1234567890123456789012",
  "workflowId": "clwf1234567890123456789012",
  "workspaceId": "clxx1234567890123456789012"
}
```

Only `workspaceId` is required. Omit `filter.isDryRun` to return both real and dry runs.

#### get_workflow_run

Gets one workflow run with its ordered step logs. Read-only and idempotent. Declares Workflow runs: Read
alone, so a client upgraded with `workflows:read` keeps it. The run's trigger payload, its data and each
step's input and output carry respondents' answers, and the run's and each step's error text can quote them
(an SMTP rejection names the address it was sent to): without Responses: Read (in the grant and in the
token's scopes) they come back as `null`, and the rest of the run (status, timing, step order) is returned
as it is.

```json
{ "runId": "clrn1234567890123456789012" }
```

#### test_workflow

Dry-runs a workflow: validates its live definition would execute and resolves the trigger's survey +
ending cards, and checks that every `send_email` survey link points to a link survey in the workspace. No
run is persisted and no side effects occur; the result reports `{ ok, problems, warnings }`. Warnings
(such as survey link Embedded Data keys the survey doesn't accept) never make `ok` false.
Annotated read-only (no world mutation). **Drafts are testable** — checking the setup before going
live is the point of a dry run — so a workflow can be tested straight after `create_workflow`. Only
**archived** workflows are rejected, with `422 invalid_workflow_state`, since they are soft-deleted.

```json
{ "workflowId": "clwf1234567890123456789012" }
```

#### create_workflow

Creates a workflow, always as a draft (only `enable_workflow` makes it live). Writes data; not
idempotent. Takes the full v3 create payload:

```json
{
  "definition": {
    "edges": [],
    "entryNodeId": "trigger",
    "nodes": [],
    "schemaVersion": 1,
    "trigger": {
      "config": { "endingCardIds": ["ending-1"], "surveyId": "clsv1234567890123456789012" },
      "id": "trigger",
      "triggerType": "response.completed",
      "type": "trigger"
    }
  },
  "name": "Notify on churn survey completion",
  "workspaceId": "clxx1234567890123456789012"
}
```

#### patch_workflow

Updates a workflow (v3 PATCH contract: top-level partial merge, no deep merge). Destructive; not
idempotent. `definition` edits are only accepted while the workflow is draft or disabled.

```json
{
  "data": { "name": "Renamed workflow" },
  "workflowId": "clwf1234567890123456789012"
}
```

#### duplicate_workflow

Duplicates a workflow as a new draft with empty run and version history. Writes data; not idempotent.

```json
{ "name": "Copy of workflow", "workflowId": "clwf1234567890123456789012" }
```

`name` is optional; if omitted the server picks a non-conflicting copy name.

#### Lifecycle tools

`delete_workflow`, `enable_workflow`, `disable_workflow`, `archive_workflow`, and `unarchive_workflow`
each take only a workflow id:

```json
{ "workflowId": "clwf1234567890123456789012" }
```

- `enable_workflow` — validates executability, snapshots an immutable version, and makes the workflow
  live. A non-executable definition is refused with `422 workflow_not_executable`.

  <Warning>Once live, the workflow runs on matching survey responses and can send emails.</Warning>

- `disable_workflow` — stops future runs.
- `archive_workflow` / `unarchive_workflow` — soft archive and restore (to draft).
- `delete_workflow` — the v3 delete returns `204 No Content`; the MCP result contains the `requestId`.

#### Webhook trigger tools

A workflow with a Webhook trigger starts a run whenever an outside system POSTs JSON to its Webhook
Secret URL. The URL is a credential (ADR 0057), so all three tools need `workflows:write`, reading
included.

- `get_webhook_url` — `{ "workflowId" }`. Returns the Secret URL, when it was last called and from
  which IP and its payload, and the expected payload with the Variables inferred from it. Its description tells the agent the
  result is a credential.
- `regenerate_webhook_url` — `{ "workflowId" }`. Replaces the URL; the old one answers 404 from the
  next call on. Audited as `webhookUrlRegenerated`.
- `set_sample_payload` — `{ "workflowId", "payload" }`. Sets the expected payload (a JSON object up
  to 100 KB, 10 levels deep) and returns its Variables. Audited as `updated` on the workflow, without the payload.

Injection assessment: the expected payload, the last call and Variable paths are caller-supplied text that reaches the
agent's context. The tools return nothing beyond the one workflow the caller can already write, and
permit nothing beyond what the caller's `workflows:write` scope and v3 authorization already allow, so
hostile text in a payload cannot cross a workspace or user boundary.

- `send_test_request` — `{ "workflowId", "stepId", "config"?, "variables"? }`. Makes one real call of an
  HTTP request step (saved settings, or the draft `config`) and returns the request, with secret header
  values masked, and the response. Not a run. Keeps the response as the step's last test response, which
  never changes the step's expected response body (ADR 0054). Shares the
  30-per-minute budget of `POST /api/v3/workflows/{workflowId}/steps/{stepId}/test-request` and is
  audited as `testRequestSent` (host and status).

Injection assessment for `send_test_request`: the response body comes from an outside server and reaches
the agent's context as untrusted text; the tool description says so. A hostile body cannot widen what
the tool does: the URL's origin is fixed by the step and Variables only fill encoded path segments
(ADR 0053), a stored secret goes only to the origin it was
set for and comes back masked, and the call needs `workflows:write` on that workflow. An agent persuaded to
point the step elsewhere, in the draft `config` or with `patch_workflow`, cannot take a stored credential
with it: the call is refused and Enable fails until someone who has the value enters it again (ADR 0051).

- `set_expected_response` — `{ "workflowId", "stepId", "body" }`. Sets an HTTP request step's expected
  response (ADR 0054): the JSON object its API answers with (up to 100 KB, 10 levels deep). Returns it with
  its Variables under `steps.<stepId>.body.*`. Later steps use those Variables, and `run_test` answers
  "Wait and use it" with this body. Calls nothing. Audited as `updated` on the workflow, with the step id
  and without the body.

Injection assessment for `set_expected_response`: the body is the caller's own JSON, stored for one
workflow the caller can already write. Hostile text in it can only name Variables in that workflow, which
an editor sees in the step's Expected response body card; it reaches no other workspace or user, and the tool
calls nothing outside Formbricks.

- `run_test` — `{ "workflowId", "payload"? }`. Runs a Webhook workflow's current draft once, at once,
  with fake effects (ADR 0049): If/else conditions are evaluated for real, emails record whom they would
  go to, HTTP requests record what they would call and, in "Wait and use it", answer with the step's
  expected response body. Nothing is sent or called. Returns the finished run (`isDryRun: true`, no
  version) with run detail per step: the branch taken, each condition matched or not, and the steps not
  taken. Uses the workflow's expected payload when `payload` is absent. Shares the 30-per-minute budget of
  `POST /api/v3/workflows/{workflowId}/test-runs` and is audited as `testRunStarted` (run id only).
  Like `get_workflow_run`, it leaves out the run's trigger payload, data, error and each step's input,
  output and error unless the caller holds Responses: Read: a Response completed test run reads an
  existing response's answers.

Injection assessment for `run_test`: the result carries the test payload's values and stored Test request
responses, untrusted text the description flags. Hostile text cannot widen what the tool does: it walks
only the caller's own draft, sends and calls nothing, returns secret header values masked, and needs
`workflows:write` on that workflow.

### Response tools

Nine tools, one per documented v3 response operation. The set mirrors the API deliberately: what an
agent can do through MCP is what an API key can do over HTTP, read off one list rather than two.

A response's contact id and its tags are response data, under Responses. Only the contact's `userId`, a
contact attribute, needs Contacts and Contact attributes at Read; without them it comes back as `null` on
`get_response` and both write tools, whose answers carry the same resource. The tag tools (`list_tags`,
`update_tag`, `merge_tags`) are a separate surface, on the Tags permission.

Every tool description states the boundary against the feedback-record tools, because
`list_feedback_records(source_id=<surveyId>)` looks like it answers the same question and does not —
see **Feedback Records And The Hub** below. The full paragraph goes on `list_responses` and
`count_responses`, where the wrong pick is both likely and quiet; the others carry a one-line form,
since a description is context every client pays for on every `tools/list`.

#### list_responses / count_responses / get_response

Read-only and idempotent. `workspaceId` is always required; `surveyId` or `contactId` narrows it, and
the `finished` and `language` filters require one of those two anchors because without one they are
unbounded scans. `list_responses` caps `limit` at 50 — below the API's 250, because an agent's binding
constraint is its context window and a response carries every answer.

```json
{
  "finished": true,
  "limit": 20,
  "surveyId": "clsv1234567890123456789012",
  "workspaceId": "clxx1234567890123456789012"
}
```

#### validate_response

A dry run of a create or patch: reports `valid`, `invalid_params`, and — when valid — the `effects` a
write would have, including the language that would be stamped and the quotas that would count. It
declares `responses:write` although it writes nothing, because it resolves the same references the
write resolves; gating it at read would make it a cheaper existence probe than the operation it
describes.

```json
{ "data": { "data": {}, "finished": true, "surveyId": "clsv…" }, "operation": "create" }
```

#### create_response / update_response

`create_response` records a real submission: webhooks, integrations, follow-ups, quotas and metering
all run. `update_response` replaces `data` and `tags` wholesale rather than merging, which is why it is
annotated `destructiveHint: true` — to add one tag, read the response and send every tag it should end
up with. Setting tags needs Responses: Write alone, as it always did.

Both take the v3 body as an opaque `data` argument and let the operation parse it, so the tool and the
route answer the same thing to a malformed body.

#### delete_response / batch_delete_responses

Both **ask before they delete**, over the multi-round-trip `input_required` flow: the first call returns
an `elicitation/create` request and an opaque `requestState`, and the client retries with the answer.

The pending confirmation is HMAC-sealed by `createRequestStateCodec` and bound to the caller, and the
handler compares the sealed `resourceId` against the arguments on re-entry. Both come back through the
client, so without that comparison a client could be asked about response A and retry the confirmation
against response B. The batch tool binds the exact id list, so a confirmation for two ids does not
carry over to a third.

`confirm: true` skips the prompt. That is not a convenience bolted on afterwards — it is the path a
2025-era client and a headless caller use, and without it those clients could not delete at all.

```json
{ "confirm": true, "responseId": "clrs1234567890123456789012" }
```

Both are `idempotentHint: true`: a response that is already gone answers the same `403` as one that was
never this caller's, so repeating the call converges rather than compounding.

#### set_responses_outcome

Marks up to 100 responses Low quality (`outcome: "lowQuality"`), or restores them (`outcome: null`), in one
transaction, over `POST /api/v3/responses/batch-outcome`. `outcome` is required, so leaving it out is never
read as a restore. Ids outside `workspaceId` are ignored, and `updated` counts the responses in scope,
including ones that already carried the outcome, so a retry reports what the first call did. Each response
that changed fires the response pipeline. It asks for no confirmation: the change is undone by the same
call with the other outcome.

The operation charges the state-mutation budget (`v3StateMutation`, 120 per minute per user or API key),
so the REST route and the tool spend from one bucket.

```json
{
  "ids": ["clrs1234567890123456789012"],
  "outcome": "lowQuality",
  "workspaceId": "clxx1234567890123456789012"
}
```

### Tag tools

`list_tags` (Tags: Read), `update_tag` and `merge_tags` (Tags: Write), over `GET /api/v3/tags`,
`PATCH /api/v3/tags/{tagId}` and `POST /api/v3/tags/{tagId}/merge`. Tags is its own permission in the
Responses category, capped by the `responses` scopes.

- `list_tags` returns each tag with `count`, the responses carrying it that the caller may read.
- `update_tag` renames a tag; a name already taken in the workspace is a `422`.
- `merge_tags` moves every response tagged `tagId` onto `newTagId`, then removes `tagId`. It is the one
  tool that removes something for good outside the confirmed deletes, allowed because no tagging is lost:
  it fixes a duplicate or a misspelling. There is no `delete_tag`.

The edit and merge tools take no workspace: the operation resolves it from the tag, and refuses a merge
across workspaces. The tag tools answer **OAuth callers only**. `/api/v3/tags` is session-only, so an
API key has never had tag access, and the tools refuse one with a `403` rather than widen what a key can do.

### Chart and dashboard tools

Twenty-one tools over the v3 chart and dashboard operations (`modules/mcp/tools/dashboards.ts`), one per
operation, minus deletion: there is no tool that deletes a chart or a dashboard, so a vague prompt such as
"clean up old charts" cannot remove anything permanently. There is no AI generation tool either — an agent
writes the chart query itself.

- **Write against the catalog.** `list_chart_fields` returns every field a chart query may use; the query
  validator refuses anything else with `invalid_params` naming each problem. `preview_chart` runs an unsaved
  chart so an agent can check it before `create_chart` saves it.
- **A chart definition needs Charts: Read alone.** `list_charts` and `get_chart` return chart definitions,
  Charts data, so they declare Charts at `read` and nothing else; the chart write tools return the chart they
  wrote under Charts: Write, which includes Read.
- **Free-form numbers need feedback access.** `preview_chart` and `list_chart_field_values` run a caller's own
  query over respondents' answers, so they declare Charts **and** Feedback records at `read`, which need
  `dashboards:read` and `feedbackRecords:read`.
  `get_chart_data` declares the same two, with one exception through `registerMcpTool`'s `{ byInput }` form:
  given a `dashboardId` it reads the chart as that dashboard shows it, and a Dashboard viewer's token (trimmed to
  `dashboards:read`, flagged `dashboardViewerOnly` at authentication) may do that on Dashboards at `read`
  alone, which needs `dashboards:read` (ADR-0025). Without `dashboardId` it is the chart-only read it always was. Each operation also checks read
  access to the chart's feedback dataset, the dashboard-bound one through `dashboard_read` for a viewer. They spend from
  the same 600/min budget as the REST data routes, and share their limit of 20 queries running at once, both
  charged inside the operation.
- **A dashboard carries its charts.** `get_dashboard` returns each widget's whole chart, so it declares
  Dashboards **and** Charts at `read` (both under `dashboards:read`), and a Dashboard viewer Dashboards alone,
  through `{ byInput }`. `duplicate_chart` declares Charts at `write`, and Dashboards at `write` too when
  it is given a `dashboardId`, since the copy then joins that dashboard as `add_chart_to_dashboard` would.
- **Dashboard filter values.** `list_dashboard_filter_values` is `GET /api/v3/dashboards/{dashboardId}/filters/{filterId}/values`:
  the values a list filter offers, narrowed by the date range, the other filters' picks and `search`, which an
  agent then passes as `picks` to `get_chart_data`. It is gated like a chart read through its dashboard —
  `dashboards:read` and `feedbackRecords:read`, or `dashboards:read` alone for a Dashboard viewer — and spends
  from the default v3 budget on every call and from the chart-query budget per Cube query on a cache miss.
- **Dashboard filter fields.** `list_dashboard_filter_fields` is `GET /api/v3/dashboards/{dashboardId}/filter-fields`:
  the embedded-data fields (`FeedbackRecords.ed_*`) of the feedback datasets the dashboard's charts read, which an
  agent uses as a filter's `field` in `set_dashboard_filters`, `get_chart_data` and `list_dashboard_filter_values`.
  A Dashboard viewer cannot call `list_chart_fields`, so this is how its agent finds them. It is gated like
  `list_dashboard_filter_values`, and spends from the default v3 budget.
- **Shared charts.** `update_chart`'s description says an edit shows on every dashboard holding the chart, and
  points at `duplicate_chart` + `update_widget` for a per-dashboard change. `duplicate_dashboard` says the copy
  shares its charts. `remove_chart_from_dashboard` says the chart is kept.
- **Rearranging.** `update_dashboard_layout` takes `{ expectedUpdatedAt, widgets: [{ widgetId, layout }] }` and is
  refused unless it lists exactly the current widgets, so it can never remove a widget by omission. A stale
  `expectedUpdatedAt` answers `409` with the current one in `details`.
- **Locked filters.** `set_dashboard_filters` takes `{ expectedUpdatedAt, filters }` and replaces the dashboard's
  locked filters — the `filters` of `PUT /api/v3/dashboards/{dashboardId}` without the rest of the save, through
  `setV3DashboardFilters`, which keeps the name and every widget. The list is the whole set: a filter is kept by
  sending it back as `get_dashboard` read it, changed by sending it changed, removed by leaving it out, and an empty
  list removes them all. A filter sent without `id` gets a new one. The input carries the PUT body's checks (at most
  10 filters, a catalog dimension or embedded-data field with an operator it allows, values within the picks
  budget), and the operation the save's: an embedded-data key none of the dashboard's charts reads answers `422`, a
  stale `expectedUpdatedAt` `409`. Locked filters are ANDed; there are no OR groups.

Every write runs through `runMcpMutation`, so it leaves the same audit event as the REST call.

### Audience tools

Five read-only, idempotent tools over the v3 Audience list operations (`modules/mcp/tools/audience.ts`), one per
operation, with no write tools. Each declares its Audience permission at Read — Contacts, Contact attributes
(keys and values), Segments, Action classes — capped by `audience:read`. The operations own the workspace check
and the Contacts entitlement (all but action classes), exactly as over REST.

| Tool                            | REST operation                          | Permission                                                                              |
| ------------------------------- | --------------------------------------- | --------------------------------------------------------------------------------------- |
| `list_contacts`                 | `GET /api/v3/contacts`                  | Contacts: Read and Contact attributes: Read (each contact carries its attribute values) |
| `list_contact_attribute_keys`   | `GET /api/v3/contact-attribute-keys`    | Contact attributes: Read                                                                |
| `list_contact_attribute_values` | `GET /api/v3/contacts/attribute-values` | Contact attributes: Read                                                                |
| `list_segments`                 | `GET /api/v3/segments`                  | Segments: Read and Contact attributes: Read (filters carry literal attribute values)    |
| `list_action_classes`           | `GET /api/v3/action-classes`            | Action classes: Read                                                                    |

- **Smaller pages.** `list_contacts` and `list_segments` default to 20 and cap at 50 (the API allows 250): a
  contact carries every attribute it has, a segment its filter tree. The key and value lists cap at 100.
- **Filters in the query's own terms.** `list_contacts` takes `filter.attributes: [{ key, operator, values }]`,
  sent as `filter[attribute.<key>][<operator>]`; the operation types each against the key's `dataType` and answers
  `invalid_params` for a wrong operator or value. An operator that compares needs `values`; only `isSet` and
  `isNotSet` take none, so a filter is never dropped silently.
- **Untrusted text.** Contact attribute values are written by end users and SDK calls. The descriptions tell the
  agent to treat them as data; nothing on our side acts on them.

### list_feedback_datasets

Lists the active feedback datasets assigned to a workspace. Read-only and idempotent. Use the
returned `id` as `datasetId` for the other feedback-record tools.

Input:

```json
{
  "workspaceId": "clxx1234567890123456789012"
}
```

Output:

```json
{
  "data": [{ "id": "clfd1234567890123456789012", "name": "Support" }],
  "meta": { "nextCursor": null, "totalCount": 1 },
  "requestId": "req_..."
}
```

### list_feedback_records

Lists feedback records in a workspace's feedback dataset. Read-only and idempotent, with opaque
cursor pagination. `datasetId` is optional when the workspace has exactly one active
dataset (the common case) and required when it has more than one.

Input:

```json
{
  "cursor": "opaque-cursor-from-previous-response",
  "datasetId": "clfd1234567890123456789012",
  "field_group_id": "grp_1",
  "field_id": "q1",
  "field_type": ["text", "rating"],
  "has_sentiment": true,
  "limit": 50,
  "order": "desc",
  "sentiment": ["negative", "very_negative"],
  "since": "2026-01-01T00:00:00Z",
  "sort": "collected_at",
  "source_id": "svy_1",
  "source_type": ["survey", "review"],
  "submission_id": "sub_1",
  "until": "2026-12-31T23:59:59Z",
  "user_id": "user_1",
  "value_id": "opt_1",
  "workspaceId": "clxx1234567890123456789012"
}
```

All filters are optional. They mirror the Hub's own `GET /v1/feedback-records` parameters, and each is
named after the record field it filters — so filtering by a `user_id` you just read in a response is
spelled the same way. An unknown filter key is rejected with a 422 rather than ignored, since a silently
dropped filter would widen the result set without saying so.

**How they combine.** Every identity filter accepts one value or a list of them. Repeating one filter
**OR**s its values; different filters are **AND**ed. So `source_type: ["survey", "review"]` with
`sentiment: ["negative"]` reads as _"(survey OR review) AND negative"_. There is no way to OR across
different filters.

| Filter                                        | Selects                                                              |
| --------------------------------------------- | -------------------------------------------------------------------- |
| `source_type`                                 | a kind of source, e.g. `survey`, `review`, `call_notes`              |
| `source_id`                                   | one survey/form/ticket                                               |
| `source_name`                                 | one source by display name                                           |
| `field_type`                                  | one field type (`text`, `nps`, `rating`, …)                          |
| `field_id`                                    | all answers to one question                                          |
| `field_group_id`                              | one grouped question (ranking, matrix, grid)                         |
| `submission_id`                               | the sibling answers given in one submission                          |
| `user_id`                                     | everything one end user submitted                                    |
| `value_id`                                    | everyone who picked one particular choice                            |
| `language`                                    | the language the feedback was given in                               |
| `sentiment`                                   | a sentiment label; only enriched records carry one                   |
| `emotions`                                    | **any** of the listed emotion labels, never all of them              |
| `since` / `until`                             | a `collected_at` range (must fall between 1970-01-01 and 2080-12-31) |
| `created_since` / `created_until`             | a `created_at` range — "what did this import bring in"               |
| `updated_since` / `updated_until`             | an `updated_at` range — "what was created or changed since"          |
| `value_date_min` / `value_date_max`           | a range over the date _answer_, not the collection time              |
| `value_number_min` / `value_number_max`       | a range over the numeric answer                                      |
| `sentiment_score_min` / `sentiment_score_max` | a sentiment score range, from -1 to 1                                |
| `has_sentiment`                               | records that do (`true`) or do not (`false`) carry a sentiment       |
| `has_emotions`                                | records that do or do not carry emotion labels                       |
| `has_translation`                             | records that do or do not have a translation                         |

Value limits mirror the Hub's: at most 100 values per filter (the enum filters cap at their own label
count instead), 255 characters per value, and 10 for a `language` tag. Crossing either bound is a 422
naming the filter, never a silent truncation to the first 100.

An empty string is **not** the same thing here as on the Hub directly: the Hub treats `?source_type=` as
identical to omitting the filter, but every string filter on this surface requires at least one
character, so an empty value is rejected rather than ignored.

<Warning>
  **Every range filter excludes records whose column is empty.** `value_number_min: 0` is not "everything" —
  it drops every text answer, because they carry no number. Likewise `sentiment_score_min: -1` means "every
  *enriched* record", not every record. To find the records enrichment has not reached, use `has_sentiment:
  false` rather than a score range.
</Warning>

<Warning>
  **A backwards range is rejected, not run as an empty query.** `value_number_min: 5, value_number_max: 1` is
  a `400` naming both bounds (e.g. `value_number_min` — "must be less than or equal to value_number_max").
  This applies to every range pair, including the timestamp ones; it is the Hub's own check relayed as-is, not
  something validated here, so the message always names the Hub's parameters.
</Warning>

**Ordering.** `sort` accepts `collected_at` (the default), `created_at` or `updated_at`, and `order` accepts
`asc` or `desc` (default `desc`). `updated_at` is ascending-only: pass `order: asc` explicitly, since the Hub answers 400 to `desc` and to an omitted `order`. Neither applies to `count_feedback_records`, which rejects them. A cursor marks a
position _within one specific ordering_, so keep `sort` and `order` identical for the whole traversal —
presenting a cursor under a different ordering is rejected rather than silently returning a page that
looks like a continuation.

`collected_at` and `created_at` diverge whenever historical data is imported: the feedback was collected
months ago but stored today. Use `created_since` for "what did this import bring in", and `since` for
"what did people tell us in this period".

`updated_at` is the third timestamp: it is stamped on create, on every correction and on every translation,
sentiment and emotion result (not on embeddings or topic assignment), so `updated_since` answers "what was created or changed since" — incremental extraction. Pair it
with `sort: updated_at, order: asc`: each page is one index range, and a record that changes mid-traversal
normally moves ahead of the cursor (returned again). A write that started before the cursor's position and
commits after it still lands behind; the run-start watermark picks it up next run. The next run's `updated_since` is when the
previous run _started_, minus an overlap — not the newest `updated_at` received, which skips a write that was
still committing when the traversal read past its timestamp. It never returns a
deleted record, since a delete leaves nothing to match; the full procedure, deletions included, is in the
v3 API introduction.

The workspace/dataset/pagination parameters (`workspaceId`, `datasetId`, `limit`, `cursor`) stay camelCase:
they name nothing in the record.

Output mirrors the Hub feedback-record shape and paginates with `meta.nextCursor`. `meta` also names the
dataset that was searched, so an empty `data` array unambiguously means that dataset holds no matching
records — a caller that let the dataset auto-resolve does not need a second call to find out which one it was:

```json
{
  "data": [
    {
      "collected_at": "2026-04-21T10:00:00.000Z",
      "dataset_id": "clfd1234567890123456789012",
      "field_id": "q1",
      "field_type": "text",
      "id": "019fa338-f494-7384-b34e-01739783d280",
      "source_type": "survey",
      "submission_id": "…",
      "value_text": "Great support!"
    }
  ],
  "meta": {
    "datasetId": "clfd1234567890123456789012",
    "datasetName": "Support",
    "limit": 50,
    "nextCursor": null
  },
  "requestId": "req_..."
}
```

### count_feedback_records

Counts the feedback records matching a filter set, without fetching them — for "how many" questions that
would otherwise mean paging through records. Read-only and idempotent. Takes the same filters as
`list_feedback_records` (no `limit`/`cursor`, and no `sort`/`order` — the Hub's count endpoint does not
accept ordering and they are rejected here), because the Hub documents its count endpoint as accepting the
same query parameters as its list endpoint; both go through one mapper in `lib/operations.ts`, so a count
always describes the same set as the equivalent list.

Input:

```json
{
  "has_sentiment": false,
  "since": "2026-01-01T00:00:00Z",
  "source_type": ["survey", "review"],
  "user_id": "user_1",
  "workspaceId": "clxx1234567890123456789012"
}
```

Output is the total and the dataset it came from — **no record content**, which is the point: a caller
asking "how many" never pulls end-user text into its context to find out.

```json
{
  "data": {
    "count": 42,
    "dataset_id": "clfd1234567890123456789012",
    "dataset_name": "Support"
  },
  "requestId": "req_..."
}
```

### get_feedback_record

Gets one feedback record by its Hub UUID. Read-only and idempotent. The record must belong to a
feedback dataset assigned to the workspace; otherwise the tool returns a generic authorization
error and never reveals whether a record id exists in another tenant.

Input:

```json
{
  "feedbackRecordId": "019fa338-f494-7384-b34e-01739783d280",
  "workspaceId": "clxx1234567890123456789012"
}
```

### create_feedback_record

Creates a feedback record in a workspace's feedback dataset. Writes data and is not idempotent, and
requires `feedbackRecords:write` (API keys need `write` or `manage`). The tenant is derived from the
resolved feedback dataset and is never taken from the request body. `submission_id` is optional — a
UUID is generated when omitted.

Input:

```json
{
  "field_id": "note",
  "field_label": "Call summary",
  "field_type": "text",
  "source_type": "call_notes",
  "value_text": "Customer asked for SSO and a longer trial.",
  "workspaceId": "clxx1234567890123456789012"
}
```

Output is the created feedback record (Hub shape) plus the MCP `requestId`.

### create_feedback_records

Creates several feedback records in one call — the batch form of `create_feedback_record`, for imports.
Writes data, is not idempotent, and requires `feedbackRecords:write`. Between 1 and 50 records per call.

The Hub has no bulk-create endpoint (its only bulk write is the delete-by-user erasure path), so this fans
out to one Hub create per record, in parallel. Two consequences are deliberate:

- **Validation is all-or-nothing.** Every record is validated before any is written, so a malformed batch
  is rejected without leaving half of it stored. `invalid_params` names the offending index, e.g.
  `records.3.value_text`.
- **Partial success is reported, not hidden.** If the Hub rejects some records — a duplicate
  `(submission_id, field_id)`, say — the created ones are returned and `meta.failures` accounts for the
  rest by index, so only those need retrying. If _nothing_ could be created, the upstream failure is
  returned as the response instead, because an empty success would read as "there was nothing to do".

The 50-record cap is an amplification bound as much as a payload one: one authorized request must not
become an unbounded burst of upstream writes.

<Warning>
  **A batch is not a submission.** Each record without a `submission_id` gets its own generated one, exactly
  as in the single-record case — so several answers that belong to the same submission (a survey response, or
  a call with both a rating and a comment) must carry the *same* `submission_id`, set by the caller. Omit it
  and they are stored as unrelated submissions, which nothing downstream can distinguish from the intended
  shape.
</Warning>

Input:

```json
{
  "records": [
    {
      "field_id": "note",
      "field_type": "text",
      "source_type": "call_notes",
      "value_text": "Asked for SSO."
    },
    {
      "field_id": "score",
      "field_type": "nps",
      "source_type": "call_notes",
      "value_number": 9
    }
  ],
  "workspaceId": "clxx1234567890123456789012"
}
```

Output:

```json
{
  "data": [{ "dataset_id": "clfd…", "id": "019fa338-…", "value_text": "Asked for SSO." }],
  "meta": {
    "created": 1,
    "datasetId": "clfd1234567890123456789012",
    "datasetName": "Support",
    "failed": 1,
    "failures": [{ "detail": "duplicate record for (tenant_id, submission_id, field_id)", "index": 1 }],
    "requested": 2
  },
  "requestId": "req_..."
}
```

Per-record failure text goes through the same relay rules as a whole-request failure: a Hub 4xx explains
itself, anything else becomes a fixed message. Each record actually created produces its own `created`
audit event — N creations are N events, not one summary.

### update_feedback_record

Corrects the value of an existing feedback record. Writes data, is annotated `destructiveHint: true` (it
overwrites a stored value; the previous one survives only in the audit log), and requires
`feedbackRecords:write` (API keys need `write` or `manage`). Only the fields sent are changed; at least one is required.

For API keys, the same dataset-exclusivity rule applies as for deletes: the key may update only a
record in a dataset assigned to exactly one workspace, where its permission unambiguously covers every
record present (ENG-2189). A shared dataset returns 403; an integration needing to update records in
both workspaces should use a workspace-scoped key per workspace. Session, OAuth and MCP-person
principals are unaffected and authorize through their organization role instead.

Updatable — the Hub's own mutable set: `value_text`, `value_number`, `value_boolean`, `value_date`,
`value_id`, `user_id`, `language`, `metadata`. The schema is `.pick()`ed from the create fields, so bounds
can't drift between creating and correcting a record.

The `value_*` field being set must be one the record's `field_type` accepts — the same table `create` enforces
(`text` takes `value_text`, `nps`/`rating`/`number` take `value_number`, `categorical` takes `value_text`
and/or `value_id`, and so on). Because `field_type` is immutable it is not part of the patch, so this is
checked against the _stored_ record and therefore reported after the ownership check, as a 422 naming the
offending field. Without it a patch could assemble what `create` rejects: putting `value_number` on a `text`
record would leave both a text and a number set, with nothing to say which one the record means. The Hub does
not enforce this itself.

**Not** updatable: a record's provenance — `source_type`, `source_id`, `source_name`, `field_id`,
`field_type`, `field_label`, `field_group_*`, `submission_id`, `collected_at`. Correcting those means
deleting the record and creating it again. The derived enrichment fields (`sentiment`, `sentiment_score`,
`emotions`, `value_text_translated`, `translation_lang_key`) are not accepted from callers either — they are
the Hub's to compute.

`metadata` is the one field that is **replaced, not merged** — the Hub assigns it wholesale, so adding a key
means sending the existing ones too. Everything else is left untouched when omitted.

Ownership is verified before the update, the same way as for get and delete: `PATCH /{id}` is another Hub
endpoint that derives the tenant from the stored record. A record deleted in the window between that check
and the write returns the same generic authorization error, not a 502 — nothing was updated and the service
is fine.

Input:

```json
{
  "feedbackRecordId": "019fa338-f494-7384-b34e-01739783d280",
  "value_text": "Actually the export works fine, it was the filter that confused me",
  "workspaceId": "clxx1234567890123456789012"
}
```

Output is the updated record.

<Warning>
  **Editing the text resets what was derived from it.** Per the Hub's contract, changing `value_text` clears
  `sentiment`, `sentiment_score`, `emotions`, `value_text_translated` and `translation_lang_key` and queues
  re-enrichment; changing `language` re-queues the translation pair only. The response reflects the
  **cleared** state, so those fields being absent right after an update means "being recomputed", not "none".
  Changing `value_text` (or a field label) also re-queues the embedding, so semantic search catches up
  asynchronously — and clearing a record's text removes its embedding, making it unsearchable.
</Warning>

### delete_feedback_record

Permanently deletes one feedback record. Writes data, is not idempotent, is annotated
`destructiveHint: true`, and requires `feedbackRecords:write` (API keys need `manage`). The
record and its derived embedding are removed with no soft delete, so this cannot be undone — the audit log
entry keeps the deleted record as its `oldObject` and is the only remaining trace.

For API keys, the dataset must be assigned to exactly one workspace — the caller's — because a key's
workspace permission can only identify whose records these are when the dataset is not shared
(ENG-2189). A shared dataset returns 403 with an explanation; an integration needing to delete from
both workspaces should use a workspace-scoped key per workspace. Session, OAuth and MCP-person
principals are unaffected and authorize through their organization role instead.

Ownership is verified before the delete: the record must belong to a feedback dataset assigned to the
workspace, and a record in another tenant is refused with the same generic authorization error as an
unknown id, without deleting anything. Single-record only — there is no bulk delete tool.

Input:

```json
{
  "feedbackRecordId": "019fa338-f494-7384-b34e-01739783d280",
  "workspaceId": "clxx1234567890123456789012"
}
```

Returns `204 No Content` on success (the tool result carries only the `requestId`).

### search_feedback_records

Searches a workspace's feedback dataset semantically: the query is embedded and compared to record
embeddings by cosine similarity, so it matches meaning rather than keywords. Read-only and idempotent.

Input:

```json
{
  "cursor": "opaque-cursor-from-previous-response",
  "limit": 10,
  "minScore": 0.5,
  "query": "checkout is confusing",
  "workspaceId": "clxx1234567890123456789012"
}
```

Output is scored matches, best first — record ids with the embedded text, not full records. Pass a
`feedback_record_id` to `get_feedback_record` for the rest of a record:

```json
{
  "data": [
    {
      "feedback_record_id": "019fa338-f494-7384-b34e-01739783d280",
      "field_label": "What can we improve?",
      "score": 0.82,
      "value_text": "I couldn't figure out how to pay"
    }
  ],
  "meta": {
    "datasetId": "clfd1234567890123456789012",
    "datasetName": "Support",
    "limit": 10,
    "minScore": 0.5,
    "nextCursor": null
  },
  "requestId": "req_..."
}
```

### find_similar_feedback_records

Finds the records most similar to a given one, by embedding distance — useful for gauging how widely a
piece of feedback is echoed. Read-only and idempotent. Same output shape as `search_feedback_records`;
the anchor record is excluded from its own results.

Input:

```json
{
  "feedbackRecordId": "019fa338-f494-7384-b34e-01739783d280",
  "limit": 10,
  "minScore": 0.5,
  "workspaceId": "clxx1234567890123456789012"
}
```

Ownership of the anchor record is verified before any neighbour is fetched (see
[Feedback Records And The Hub](#feedback-records-and-the-hub)).

<Note>
  Both search tools need embeddings, which are optional in the Hub. Without `EMBEDDING_PROVIDER` and
  `EMBEDDING_MODEL` configured on **both** the Hub API and the Hub worker they return `503` with that
  instruction as the detail. Embedding is also asynchronous and only covers records that have text, so a
  record created moments ago is not searchable yet; `find_similar_feedback_records` reports that as a `409`
  rather than an empty result, distinguishing "still being embedded, retry" from "no text, so there is no
  embedding to wait for" — the latter also covers text cleared by an update.
</Note>

`limit` (1–100, default 10) and `minScore` (0–1, default 0.5) are validated by Formbricks rather than
passed straight through: the Hub silently coerces out-of-range values to its own defaults, which would
return something other than what was asked for. The default `minScore` of 0.5 is Formbricks' own — the Hub
defaults to 0.7, which is strict enough that a fair paraphrase often falls just below it.

## Relationship to V3 Workflows API

Like the survey tools, workflow tools run no custom database queries — each calls the shared,
framework-agnostic `@formbricks/workflows` handlers used by the v3 REST routes:

| MCP Tool             | REST Contract                                   |
| -------------------- | ----------------------------------------------- |
| `list_workflows`     | `GET /api/v3/workflows`                         |
| `get_workflow`       | `GET /api/v3/workflows/{workflowId}`            |
| `list_workflow_runs` | `GET /api/v3/workflows/runs`                    |
| `get_workflow_run`   | `GET /api/v3/workflows/runs/{runId}`            |
| `test_workflow`      | `POST /api/v3/workflows/{workflowId}/test`      |
| `create_workflow`    | `POST /api/v3/workflows`                        |
| `patch_workflow`     | `PATCH /api/v3/workflows/{workflowId}`          |
| `duplicate_workflow` | `POST /api/v3/workflows/{workflowId}/duplicate` |
| `delete_workflow`    | `DELETE /api/v3/workflows/{workflowId}`         |
| `enable_workflow`    | `POST /api/v3/workflows/{workflowId}/enable`    |
| `disable_workflow`   | `POST /api/v3/workflows/{workflowId}/disable`   |
| `archive_workflow`   | `POST /api/v3/workflows/{workflowId}/archive`   |
| `unarchive_workflow` | `POST /api/v3/workflows/{workflowId}/unarchive` |
| `get_webhook_url` | `GET /api/v3/workflows/{workflowId}/webhook` |
| `regenerate_webhook_url` | `POST /api/v3/workflows/{workflowId}/webhook/regenerate` |
| `set_sample_payload` | `PUT /api/v3/workflows/{workflowId}/sample` |
| `send_test_request` | `POST /api/v3/workflows/{workflowId}/steps/{stepId}/test-request` |
| `set_expected_response` | `PUT /api/v3/workflows/{workflowId}/steps/{stepId}/expected-response` |
| `run_test` | `POST /api/v3/workflows/{workflowId}/test-runs` |

## Relationship to V3 Creatives API

The creative tools call the same operations as the REST routes (`app/api/v3/creatives/lib/operations.ts`):

| MCP Tool             | REST Contract                                   |
| -------------------- | ----------------------------------------------- |
| `list_creatives`     | `GET /api/v3/creatives`                         |
| `get_creative`       | `GET /api/v3/creatives/{creativeId}`            |
| `get_creative_stats` | `GET /api/v3/creatives/{creativeId}/stats`      |
| `create_creative`    | `POST /api/v3/creatives`                        |
| `patch_creative`     | `PATCH /api/v3/creatives/{creativeId}`          |
| `delete_creative`    | `DELETE /api/v3/creatives/{creativeId}`         |
| `duplicate_creative` | `POST /api/v3/creatives/{creativeId}/duplicate` |
| `archive_creative`   | `POST /api/v3/creatives/{creativeId}/archive`   |
| `restore_creative`   | `POST /api/v3/creatives/{creativeId}/restore`   |

The creative schemas are generated from the contract (`@formbricks/api-v3-schemas`), so the tools' input
and output schemas follow it through `pnpm api:v3:sync` rather than by hand.

## Relationship to V3 Surveys API

The MCP server does not run custom survey database queries. Each tool calls the shared server-only v3
survey operations used by the REST routes:

| MCP Tool                     | REST Contract                                       |
| ---------------------------- | --------------------------------------------------- |
| `list_surveys`               | `GET /api/v3/surveys`                               |
| `get_survey`                 | `GET /api/v3/surveys/{surveyId}`                    |
| `create_survey`              | `POST /api/v3/surveys`                              |
| `validate_survey`            | `POST /api/v3/surveys/validate`                     |
| `generate_survey`            | `POST /api/v3/surveys/generate`                     |
| `patch_survey`               | `PATCH /api/v3/surveys/{surveyId}`                  |
| `edit_survey_blocks`         | `PATCH /api/v3/surveys/{surveyId}/blocks`           |
| `set_survey_block_order`     | `PUT /api/v3/surveys/{surveyId}/blocks/order`       |
| `delete_survey`              | `DELETE /api/v3/surveys/{surveyId}`                 |
| `get_workspace_custom_css`   | `GET /api/v3/workspaces/{workspaceId}/custom-css`   |
| `patch_workspace_custom_css` | `PATCH /api/v3/workspaces/{workspaceId}/custom-css` |

When the v3 OpenAPI contract changes, update the MCP schemas and this page together. The v3 spec is
hand-authored under `docs/api-v3-reference/src/` and bundled to `docs/api-v3-reference/openapi.yml`. For
resources whose schemas are generated (Responses today), the tools' output schemas follow the contract through
`pnpm api:v3:sync`; their input schemas and this page are still updated by hand. See
[API v3 Schema Generation](/development/technical-handbook/api-v3-schema-generation).

## Feedback Records And The Hub

Feedback-record tools do not map to a v3 REST route. They call the shared server-only Hub service
(`@/modules/hub/service`) — the same client the Unify Feedback UI uses — and enforce the same
`feedbackDirectories` Enterprise entitlement.

A feedback record lives in the Formbricks Hub, addressed by an opaque tenant id. Every tool
resolves that tenant server-side: it authorizes the caller's access to `workspaceId`, checks the
`feedbackDirectories` license, then maps the workspace to its assigned feedback dataset — the
`FeedbackDirectory` id **is** the Hub tenant id, and it is surfaced to callers as `dataset_id`.

Assignment is a join table, but the application enforces at most one _non-archived_ directory per
workspace, so in practice `datasetId` can be omitted and the single active dataset is used.
It becomes required only if a workspace somehow has several active directories, in which case the tools
return `400` rather than guessing. A tenant id is never accepted from tool input.

Three Hub endpoints — get, delete, and similar — take a bare record id and derive the tenant from the
stored record, delegating record-level authorization to the product. So `get_feedback_record`,
`delete_feedback_record` and `find_similar_feedback_records` all retrieve the record first and verify its
tenant — the named dataset when one was given, otherwise any dataset the workspace owns — before acting.
A foreign record and an unknown record produce the same generic authorization error, so record ids cannot
be probed across tenants. `search_feedback_records` instead has the resolved tenant injected into the Hub
query, like `create_feedback_record`.

## Limitations

- OAuth is user-delegated only. Machine-to-machine client credentials for MCP are not supported.
- OAuth access tokens must be JWTs audience-bound to `/api/mcp`; opaque MCP access token introspection is not
  accepted by the MCP route.
- API-key authentication remains supported for compatibility and fallback use.
- The MCP server exposes only the survey, creative, workflow, response, feedback-record, chart and dashboard operations listed on this page.
- Creative tools require a self-hosted Enterprise license that includes Creatives; elsewhere they answer
  403 `creatives_not_entitled`. In wind-down (the license lost Creatives) only reads, pause, close and delete
  are allowed. `POST /api/v3/creatives/pause` has no tool.
- Survey and workflow tool coverage depends on the current v3 Surveys and Workflows REST endpoint
  coverage; feedback-record tool coverage depends on the Hub feedback-records API.
- `enable_workflow` makes a workflow live and can trigger email sending; treat it as a high-impact
  mutation when granting agents write access.
- `create_workflow` requires a complete workflow `definition` (schema version, trigger, entry node);
  it is created as a draft and only `enable_workflow` can make it live.
- Feedback-record tools require the `feedbackDirectories` Enterprise entitlement and a feedback
  directory assigned to the workspace; without either they return 403 / 422.
- A feedback record's **provenance** is immutable: `update_feedback_record` changes values, users, language
  and metadata, but not which source, question or submission a record belongs to, nor when it was
  collected. The derived enrichment fields are the Hub's to compute and are never accepted from callers.
- `delete_feedback_record` deletes one record at a time. The Hub's bulk and delete-by-user endpoints are
  deliberately not exposed: they are erasure operations whose blast radius does not belong on an agent
  surface. There is deliberately no batch _delete_ to match `create_feedback_records`.
- Counting and filtering cover the Hub's own filter set only. There is no aggregation by sentiment or
  emotion, and semantic search cannot be narrowed by source or date — the Hub's search endpoint takes only
  a query and a tenant. Those need Hub-side support first.
- The search tools require an embedding model configured on the Hub API **and** the Hub worker; without
  one they return 503. Embedding is asynchronous and covers only records with text.
- The survey, workflow, feedback-record and Audience tools advertise no result shape (`outputSchema`), so a
  client has to infer theirs from an example. An output schema is built from the v3 resource schema and never
  retyped, and none exists yet for those resources.
- The response tools cover the v3 operations and nothing more: there is no tool that adds or removes a
  single tag, because `PATCH` replaces the tag set wholesale and such a tool would be a read-modify-write
  wrapper with its own race rather than an operation.
- `create_survey` creates link surveys only. In-app survey creation and distribution settings are not
  part of the current v3 create operation.
- `edit_survey_blocks` and `set_survey_block_order` operate on whole blocks. There is no element-level
  operation: elements travel inside the block payload, and going finer would reintroduce the same
  resend problem one level down.
- Ordering is validated as a delta on the **patch family only**: a change may not _introduce_ a
  `#recall:` that points forwards, a logic condition reading a later block, or a `requireAnswer`
  targeting an earlier one (`misordered_reference`). Violations a survey already contains are left
  alone, so an existing survey never becomes unpatchable — enforcing the full set would repeat the
  ENG-3070 failure. `create_survey` is deliberately not covered: tightening it would reject payloads
  that are valid today, which needs its own versioned rollout.
- `stored_survey_invalid` (422) means the _stored_ survey cannot be read as a v3 document (legacy
  questions, no v3 block list, a shape that does not parse); the reported paths are into the survey,
  not the request — repair it in the editor. A survey that reads fine but already fails validation
  stays patchable: issues it already had are not refused, only issues a patch newly introduces
  (ENG-3975). Publishing a draft is the exception — it is refused as `stored_survey_invalid` until
  the survey passes.
- `patch_survey` follows the v3 PATCH contract: top-level partial document updates only, no JSON Patch,
  and no nested deep merge. Provided top-level objects and arrays replace their whole subtree and can
  remove omitted nested entries.
- `validate_survey` validates payload shape and references; it does not create languages, survey
  versions, or surveys.
- Query-string credentials are rejected; use headers for API keys.
- Large request bodies are rejected before the MCP handler using the same body-size policy as v3 APIs.
- A whole MCP request may contain at most 50,000 object members and array entries combined, including
  protocol metadata and all calls in a legacy batch. An over-budget request returns HTTP 400 with
  JSON-RPC code `-32602` before any tool executes. Reduce the arguments or split batches into smaller
  requests. Existing limits of 2 MiB, 1,000 entries per array, and 256 nesting levels still apply.
- Legacy JSON-RPC batches are limited to 100 messages by SDK 2.3. Larger batches return HTTP 400 with
  JSON-RPC code `-32600`; split them into requests of at most 100 messages. Individual calls are unaffected.
- Tool arguments are strict: undeclared keys are rejected rather than ignored (see [Tool
  Arguments](#tool-arguments)).
- Resources and prompts are not exposed — the server registers tools only, so there is no MCP resource
  for the survey document contract yet.
- `subscriptions/listen` is refused (`maxSubscriptions: 0`). The 2026-07-28 revision replaced the GET SSE
  endpoint with a long-lived POST-response stream, but with no resources registered and no list-changed
  notifications emitted, such a stream could never deliver anything — it would just hold a connection.
  A client that opens one gets `Subscription limit reached`; the list endpoints remain the way to see
  current tools, prompts and resources.

## Implementation Files

- `apps/web/app/api/mcp/route.ts`
- `apps/web/modules/mcp/auth.ts`
- `apps/web/modules/mcp/server.ts`
- `apps/web/modules/mcp/permissions.ts` (the permission registry: categories, permissions, scope families, access levels)
- `apps/web/modules/mcp/tools/guard-permissions.ts` (`registerMcpTool`, the permission gate)
- `apps/web/modules/mcp/tools/surveys.ts`
- `apps/web/modules/mcp/tools/workspaces.ts` (workspace discovery and the workspace custom CSS tools)
- `apps/web/modules/mcp/tools/feedback-records.ts`
- `apps/web/modules/mcp/tools/schemas.ts`
- `apps/web/modules/mcp/tools/workflows.ts`
- `apps/web/modules/mcp/tools/workflow-schemas.ts`
- `apps/web/modules/mcp/tools/creatives.ts`
- `apps/web/modules/mcp/tools/tags.ts`, `tag-schemas.ts` and `tag-output-schemas.ts`
- `apps/web/app/api/v3/tags/lib/operations.ts`
- `apps/web/app/api/v3/surveys/generate/operations.ts` (survey generation, shared by the REST route and `generate_survey`)
- `apps/web/modules/mcp/tools/creative-schemas.ts` and `creative-output-schemas.ts`
- `apps/web/app/api/v3/creatives/lib/operations.ts`
- `apps/web/app/api/v3/surveys/lib/operations.ts`
- `apps/web/app/api/v3/workspaces/lib/custom-css.ts` (workspace custom CSS operations)
- `apps/web/app/api/v3/surveys/blocks.ts` (pure block op-application and reorder logic)
- `apps/web/app/api/v3/workflows/lib/context.ts` (adapter to the `@formbricks/workflows` handlers)
- `apps/web/app/api/v3/feedbackRecords/lib/operations.ts`
- `apps/web/app/api/v3/feedbackRecords/lib/access.ts` (tenant resolution + per-record ownership guard)
- `apps/web/app/api/v3/feedbackRecords/lib/errors.ts` (Hub error → v3 problem mapping)
