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

# MCP server

> OAuth 2.1 Model Context Protocol server exposing session and workspace tools to Claude.ai, ChatGPT and other clients.

`/mcp` (→ `/api/mcp`) exposes Kair Voice's session/workspace data to Model
Context Protocol clients — Claude.ai, ChatGPT, `braid-desktop`, or any
spec-compliant client — over OAuth 2.1. Built on
[PR #55](https://github.com/meldtech/kair-voice/pull/55).

## What we have

**Protocol** — the 2026-07-28 MCP spec via the official `rmcp` SDK (v3.2.0),
hosted through `poem`'s `tower-compat` feature. `get_info()` advertises
title `Braid` and `icons` pointing at the public Braid mark on the
frontend origin (PNG 192 plus SVG), so connectors such as Claude should
not fall back to a leftover K favicon. Clients should use
`server/discover` and per-request `_meta` (`tools/list`, `tools/call`).
Some connectors still POST legacy `initialize`; this server advertises
2026-07-28 only, so that handshake does not succeed here (JSON-RPC
`unsupported_protocol_version`, HTTP 200). No `resources`/`prompts`/
`sampling`/`logging` capabilities (out of scope for v1).

**Host allowlist** — rmcp's Streamable HTTP transport rejects non-loopback
`Host` headers with HTTP 403 unless `allowed_hosts` is set. `/mcp` passes
the public API hostname from `app.public_api_url` (plus loopback for local
dev). A mismatch here looks like "valid OAuth token, then every
`POST /api/mcp` is 403" and does not hit application auth logs.

**Auth** — OAuth 2.1 with the resource-indicator pieces MCP requires on top
of the pre-existing authorization server (PR #49):

* RFC 8707 resource binding: an access token minted for an MCP flow carries
  an `aud` claim; `/mcp` rejects any token whose `aud` doesn't match its own
  canonical resource URI, even if otherwise valid.
* RFC 9207 `iss` parameter on every `/oauth/authorize` redirect.
* RFC 8414 / RFC 9728 discovery documents at
  `/.well-known/oauth-authorization-server` and
  `/.well-known/oauth-protected-resource`, reachable at the true origin
  root on every stack (PR preview, staging, production).
* Client ID Metadata Documents (CIMD): a `client_id` that's an HTTPS URL is
  resolved by fetching and validating that URL's JSON document (RFC 7591
  shape: `client_name` + `redirect_uris`), cached in Redis with a 1-hour
  TTL. `/oauth/consent-context` resolves that document so the consent
  page can show `client_name` plus the client host rather than the raw
  URL. Coexists with `braid-desktop`'s pre-registered client — CIMD is only
  attempted when `client_id` looks like an HTTPS URL.

**Tools** (6, all thin wrappers over existing access-controlled routes —
no new query paths):

| Tool | Wraps | Audited |
| - | - | - |
| `search_sessions` | `routes/dashboard/dashboard_routes_search.rs` scoping + search | No (metadata only) |
| `list_workspaces` | `routes/workspace/workspace_routes_helpers.rs` (`list_workspaces_for_user`) | No (metadata only) |
| `get_session_summary` | `get_session_impl`, incl. `can_view_session_content` gate | Yes |
| `ask_workspace` | `ModeratorAgent` (rag crate) | Yes |
| `list_topics` | `list_workspace_topics_impl` | Yes |
| `get_topic_history` | `get_topic_impl` | Yes |

**Audit log** — `mcp_tool_calls` (user, client, tool, timestamp,
result summary) for the two content-exposing tools, independent of the
existing row-change audit triggers.

**Feature flag** — `VITE_MCP_INTEGRATION_ENABLED` gates the Settings UI
card only (frontend build-time flag). The backend itself is **not** gated —
`/mcp` and the discovery endpoints are live as soon as this is deployed,
regardless of the flag.

## Verification performed

Confirmed against a real running stack (`kair-dev-builder` locally, then a
real HTTPS PR-preview deployment at `pr55.kair.is`) — not just `cargo
check`:

* Discovery documents reachable and correct on every stack.
* Unauthenticated / wrong-audience / no-audience requests → 401.
* `server/discover`, `tools/list`, `tools/call` for all 4 tools against
  real data.
* `mcp_tool_calls` row lands correctly for audited tools.
* Cross-user access control (a non-member admin gets a scrubbed shell, not
  a leak, matching existing REST semantics).
* Full real OAuth round trip through a browser: magic-link login → CIMD
  client resolution (a public test document) → consent approval → `iss`
  redirect → PKCE code exchange → token with the correct `aud`.

### Bugs found and fixed during verification

None of these were caught by `cargo check` — only by running the real
stack:

1. **`jsonwebtoken`'s default `Validation` rejected every audience-bound
   token outright** (`validate_aud: true` with no configured audience =
   automatic `InvalidAudience`, before our own check even ran). Fixed in
   `util/auth.rs`.
2. **The task-local auth handoff never reached `call_tool`** —
   `StreamableHttpService` dispatches request handling on its own tokio
   tasks, so a `tokio::task_local!` scoped around the outer request future
   never propagated. Replaced with rmcp's documented
   `RequestContext::extensions` → `http::request::Parts::extensions`
   mechanism.
3. **`/.well-known/*` wasn't routed to the API on any stack** — registered
   at the true origin root per spec, but PR-preview nginx only proxied
   `/api/`, and staging/production Traefik only had a `PathPrefix(/api)`
   router. Fixed with new nginx/Traefik routes on all three.
4. **PR-preview configs never set `public_api_url`** — discovery docs
   advertised the unreachable `http://0.0.0.0:8000`. Fixed in
   `render_pr_config` (`kair-cli`).
5. **The real consent screen dropped the `resource` param** — fully wired
   on the backend, but `oauth/authorize/+page.svelte` never read or
   forwarded it, so every MCP client going through actual sign-in would
   get a token with no `aud` claim at all. Fixed in `oauth.ts` and the
   consent page.

### Host header 403 (rmcp DNS-rebinding check)

`403 Forbidden: Host header is not allowed` on `POST /api/mcp` after a
successful token exchange is rmcp 3.2.0's default loopback-only
`allowed_hosts` list, not Cloudflare WAF. Unauthenticated calls still
return 401 because our bearer check runs first. Staging and production
must include the public API host (see `mcp_allowed_hosts`). Protocol
version mismatches return 400 / JSON-RPC, not 403.

### Browser / webview CORS (`request-origin not allowed`)

The global poem CORS middleware only allows Braid frontend origins and
sets `Access-Control-Allow-Credentials`. A webview client that sends
`Origin: https://sesameai.app` (or Claude's origin) was rejected with
HTTP 403 `request-origin not allowed` *before* bearer auth, which looks
like a network `fetch failed` and leaves no MCP logs. `/api/mcp` is
wrapped outside that allow-list: any `Origin` is reflected, credentials
mode is off, OPTIONS is answered without auth, and unauthenticated POST
returns 401. rmcp `Host` checks are unchanged.

## Recommended before wider rollout

Externally reviewed after the first pass (see attribution note at the
bottom) — that review reprioritised the list below and added the GDPR
section, which the original pass didn't cover at all: verification
confirmed the *mechanism* works, not that the data it governs is handled
in a way that would satisfy a DPO reviewing this before it goes in front
of external clients like Claude.ai or ChatGPT.

### Hard gate — do not flip `VITE_MCP_INTEGRATION_ENABLED` on for external clients without this

**Scope enforcement.** `RequireAuth`'s `.workspace_id()`/
`.organisation_id()` are only populated for API-key auth — an
OAuth-issued JWT gets no automatic workspace restriction. A valid,
correctly-audience-bound token can call any of the 4 tools against any
workspace the underlying user account can access, same as their web
session. This is not a theoretical residual risk sitting behind a feature
flag — it *is* the authorisation model in production the instant the flag
flips on for a client outside the org. Real scope narrowing (a scope
string format, per-tool checks, a selectable-scopes consent screen) is
required before any externally-facing client (Claude.ai, ChatGPT) is
enabled; the backend kill switch below is a mitigation for this gap, not
a substitute for closing it.

### Security & reliability

1. **Backend kill switch.** `VITE_MCP_INTEGRATION_ENABLED` only hides the
   UI card — there's no runtime toggle for `/mcp` or CIMD support itself.
   Given CIMD lets any HTTPS-URL client register (not just pre-vetted
   ones) and the scope gap above, a config-driven kill switch gating route
   registration in `main.rs` would let it be shut off instantly without a
   revert-and-redeploy cycle.
2. **Automated tests.** Everything above was verified by hand (curl, a
   real browser) — there is currently no `#[test]` coverage for the
   auth-critical logic: `mcp_auth::authenticate` (right/wrong/missing
   audience, malformed token) and `oauth_cimd::resolve_cimd_client` (SSRF
   guards, size cap). Without tests, a future refactor could silently
   reintroduce either bug found above.
3. **`get_session_summary`'s admin-shell behavior, reconsidered for MCP
   specifically — treat as blocking, not advisory.** A non-member admin
   without an active elevation grant gets a scrubbed shell (title visible,
   content blanked, `elevation_required: true`) — correct and intentional
   for the REST web UI, which pairs it with a visible "request audited
   access" affordance. An MCP client is an agent acting on that admin's
   behalf, and could enumerate session titles across every workspace the
   admin lacks elevation for, silently and at scale, with none of the
   human friction the web UI provides — exactly the kind of automated
   processing GDPR's data-minimisation principle exists to prevent.
4. **Rate limiting on `ask_workspace` — a data-minimisation control, not
   just a cost control.** The one tool that hits the LLM agent —
   genuinely expensive per call — has no per-user or per-client rate
   limit, and is reachable by any CIMD client a user approves. Beyond
   cost, an unlimited LLM-backed query tool is a bulk personal-data
   extraction vector.
5. **CIMD's DNS-rebinding gap.** SSRF guards are hostname-based (reject
   loopback/private/`.local`, HTTPS-only, no redirects, size cap, short
   timeout) but don't pin the resolved IP — a hostname that resolves
   differently between the check and the actual `reqwest` connect isn't
   covered. Already flagged in code; needs a custom resolver to close
   properly.

### GDPR / data governance

Not covered by the original pass — the mechanism was verified to work,
not that it satisfies data-protection obligations.

* **Client accountability blocks breach investigation.**
  `mcp_tool_calls.client_id` always resolving to `"unknown"` isn't just an
  audit-completeness gap — it undermines the Article 5(2) accountability
  requirement directly. If a CIMD client is later found malicious, the
  audit trail can't attribute the calls that caused harm to a specific
  client, which is a precondition for satisfying an Article 33 breach
  investigation. Fixing this means adding a `client_id` claim to
  `util::auth::Claims` and threading it through
  `create_jwt_with_expiry_minutes_and_aud`/`issue_tokens` in
  `oauth_routes.rs`.
* **Audit log content and retention.** `mcp_tool_calls.result_summary` for
  `ask_workspace` can contain personal data drawn from session
  transcripts, since the tool queries an LLM pipeline over that content.
  There's currently no stated retention period, legal basis, or purge
  path for this table specifically — Article 5(1)(e) storage limitation
  applies to it independently of whatever retention rules govern the
  underlying sessions.
* **Third-party processor status.** Once approved as MCP clients, Claude.ai
  and ChatGPT become recipients of session data through `ask_workspace`
  and `get_session_summary`. Open question: is there a data processing
  agreement with the operators of those platforms, and does a one-click
  "Allow" on the OAuth consent screen constitute informed consent under
  GDPR standards, given the recipient is a third-party AI system that may
  retain or further process the data? A generic OAuth permission grant is
  a weak substitute for the specificity GDPR expects here.
* **CIMD weakens consent quality.** Any HTTPS URL can become a registered
  client — a known trust-boundary characteristic of the MCP ecosystem
  generally, not specific to this implementation, but it compounds the
  point above. A user approving an unvetted, self-declared client isn't
  meaningfully informed about who is receiving their data, which weakens
  the legal basis for that specific disclosure. The consent page shows
  the metadata `client_name` (self-asserted, sanitised, capped, rendered
  as text) in bold and always shows the `client_id` host underneath, so
  a client cannot pass itself off as "Silt" without also showing
  `silt.example` (or whoever actually hosts the document).
* **Revocation is a consent-withdrawal gap, not just an incident-response
  gap.** No admin-facing way yet to revoke a specific CIMD client's
  outstanding tokens short of waiting out the access-token TTL. Consent
  must be as easy to withdraw as it was to give (Article 7(3)) — a user
  who revokes access in Settings while an attacker's client still holds a
  live token hasn't actually had that withdrawal honoured.
* **No redaction/filtering layer on `ask_workspace` output** before it
  crosses the system boundary to an external client. Worth confirming
  whether session content can contain categories of personal data that
  should never reach a third-party AI processor regardless of consent
  scope.

***

*The "Recommended" section above incorporates an external review of this
document's first draft, which reordered priorities (scope enforcement
above the kill switch) and added the entire GDPR/data-governance
subsection.*


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