Skip to content

Every analytics tool wants a subscription. And your data. I built Twiligent instead. YouTube stats. Instagram stats. One dashboard. Runs locally on your machine.

docs(mcp): document the endpoint, access routes, tables and consent flow

spacesdrive5483b89ddfda
diff --git a/DECISIONS.md b/DECISIONS.md
index e8939b9..e0019f4 100644
--- a/DECISIONS.md
+++ b/DECISIONS.md
@@ -1098,3 +1098,25 @@ New row ids come from `crypto.randomUUID()` (`newRowId()` in `backend/lib/ids.ts
**Trade-offs:**
- Contributors install the plugins once and accept the workspace trust prompt; the Trail of Bits marketplace follows `main`, the Cloudflare skill is pinned to a commit.
- Connecting Instagram needs the app and the Worker on the same version, since the app now finishes the sign-in. The YouTube connection (#147) uses the same pattern.
+
+---
+
+## ADR-051: An MCP server on the Worker, signed in by access tokens or Supabase's OAuth server
+
+**Date:** 2026-11-05
+**Status:** Accepted
+
+**Decision:** The Worker serves a Model Context Protocol endpoint at `POST /mcp` (#146). It is stateless and answers JSON only: no sessions, no streams, both the 2026-07-28 protocol (`server/discover`, protocol headers) and the older initialize handshake. Two credentials sign a client in: personal access tokens created in Settings, Claude (stored as SHA-256 hashes, read or write, optional expiry), and Supabase Auth's OAuth 2.1 server for Claude's apps, with Twiligent's own `/oauth/consent` page and a per-client grant in `mcp_client_grants`. Each tool is a thin wrapper over one existing user-scoped service. Read-only callers never see write tools; publishing and deleting need an HMAC confirmation token bound to the user, the tool and the exact arguments; tool calls have a 25 second deadline, a 40,000 character result cap and a per-user token bucket; write calls are audited.
+
+**Context:** The owner wants Claude to read analytics and manage publishing for the account, with least privilege and confirmation before public or destructive actions. Claude Code accepts a bearer header; claude.ai, Desktop and mobile accept only OAuth for remote servers. The Worker runs on the Free plan (10 ms CPU, 50 subrequests), which rules out long-lived streams and server-side sessions.
+
+**Alternatives considered:**
+- Building an OAuth authorization server into the Worker. It would add client registration, code and refresh token storage and key rotation to a self-hosted app; Supabase Auth already provides them for the same users.
+- Accepting the app's own session token. A token copied from a browser would then carry full access with no per-client permission or way to remove one client; only tokens with a `client_id` claim are accepted.
+- Relying on the client's confirmation prompts (elicitation or tool annotations). They are hints the server cannot verify, and text in a caption could ask a model to skip them; the confirmation token is checked by the server.
+- A separate MCP Worker. It would duplicate the services, configuration and rate limits for one endpoint.
+
+**Trade-offs:**
+- Claude's apps need the owner to turn on Supabase's OAuth server and set `MCP_OAUTH_ENABLED`; access tokens work without it.
+- Confirmations need `TOKEN_ENCRYPTION_KEY`; without it the confirming tools refuse to run.
+- Stateless JSON means no server-initiated messages or progress notifications; long work such as YouTube uploads is a background job the tools start and poll.
diff --git a/docs/architecture/OVERVIEW.md b/docs/architecture/OVERVIEW.md
index 2cb2716..35cf714 100644
--- a/docs/architecture/OVERVIEW.md
+++ b/docs/architecture/OVERVIEW.md
@@ -28,6 +28,8 @@
│ │ GET /api/auth/instagram/callback, │
│ │ POST /api/auth/email-hook (signed by Supabase Auth), │
│ │ GET/POST /api/webhooks/instagram (signed by Meta) │
+│ ├── MCP: POST /mcp (Claude clients): requireMcpAuth (access │
+│ │ token or approved OAuth client) -> mcp limit -> tools │
│ ├── Protected (/api/*): requireAuth -> rate limits │
│ │ -> route table -> controller -> service -> repository │
│ └── Errors: errorHandler -> { success, code, message, ... } │
@@ -59,6 +61,7 @@
│ tion_* │ │ │
│ audit_ │ │ │
│ events │ │ │
+│ mcp_* │ │ │
│ │ │ │
│ auth: │ │ │
│ users │ │ optional│
diff --git a/docs/architecture/backend/MIDDLEWARE.md b/docs/architecture/backend/MIDDLEWARE.md
index 8af3f5c..6bbec14 100644
--- a/docs/architecture/backend/MIDDLEWARE.md
+++ b/docs/architecture/backend/MIDDLEWARE.md
@@ -11,7 +11,9 @@ Request arrives
requestContext app.use('*', requestContext) middleware/requestContext.ts
3. securityHeaders app.use('*', securityHeaders) middleware/securityHeaders.ts
4. injectClients app.use('*', injectClients) middleware/clients.ts
- 5. rateLimit(ip) app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp)) middleware/rateLimit.ts
+ 5. rateLimit(ip) app.use('/api/*' and '/mcp', rateLimit(RATE_LIMIT_RULES.ip, clientIp)) middleware/rateLimit.ts
+ MCP endpoint app.post('/mcp', requireMcpAuth, rateLimit(mcp), handleMcpMessage) middleware/mcpAuth.ts
+ GET and DELETE /mcp answer 405; /.well-known/oauth-protected-resource(/mcp) answer the metadata
public routes app.route('/api', publicRoutes) health check, OAuth callback (+ rateLimit(oauth)),
email hook (+ verifyAuthHook) middleware/authHook.ts
Instagram webhook POST (+ verifyMetaWebhook) middleware/metaWebhook.ts
@@ -197,6 +199,22 @@ A failure throws `UnauthorizedError` (401). Meta's notifications carry no timest
---
+## MCP Authentication
+
+**Source:** `backend/middleware/mcpAuth.ts` (`requireMcpAuth`), with `services/mcpAccessService.ts` and `lib/jwtClaims.ts`
+**Applied to:** `POST /mcp` only, after `rateLimit(ip)` and before `rateLimit(mcp)`
+
+The MCP endpoint takes credentials a Claude client can hold, never the app's own session token:
+
+1. A request with an `Origin` other than `https://claude.ai`, `https://claude.com` or the app's allowed origins is refused with `403`, so a web page cannot drive the endpoint from someone's browser.
+2. A bearer token starting `twl_` is a personal access token: its SHA-256 hash is looked up in `mcp_access_tokens`, and a revoked or expired one is refused.
+3. Any other bearer token is checked with Supabase Auth (`auth.getUser`). It must carry a `client_id` claim, which only tokens issued by Supabase's OAuth server have, and the person must have approved that client (`mcp_client_grants`); otherwise `401` or `403`.
+4. On success it sets `userId` (the same variable `requireAuth` sets, so every repository scopes by it) and `mcpPrincipal` (`{ userId, permission, via }`). The permission decides which tools the caller sees and may run.
+
+A `401` carries `WWW-Authenticate: Bearer realm="twiligent"`, and `resource_metadata="<backend>/.well-known/oauth-protected-resource/mcp"` when `MCP_OAUTH_ENABLED` is `true`, which starts sign-in in Claude's apps. Failures use a JSON-RPC error body, not the API's.
+
+---
+
## Adding New Middleware
Place new middleware files in `backend/middleware/`. Follow this pattern:
diff --git a/docs/architecture/backend/RATE_LIMITING.md b/docs/architecture/backend/RATE_LIMITING.md
index 858b317..c384b92 100644
--- a/docs/architecture/backend/RATE_LIMITING.md
+++ b/docs/architecture/backend/RATE_LIMITING.md
@@ -31,10 +31,11 @@ Defined in `backend/lib/rateLimit/rules.ts`.
| Rule | Applies to | Key | Algorithm | Limit |
|---|---|---|---|---|
-| `ip` | Every `/api` request | Client IP; IPv6 by /64 | Sliding window counter | 300 per minute |
+| `ip` | Every `/api` request and `/mcp` | Client IP; IPv6 by /64 | Sliding window counter | 300 per minute |
| `user` | Every protected request | User id from the verified JWT | Token bucket | Bursts of 120, refills 2 per second |
| `quota` | `POST /accounts`, `/accounts/instagram`, `/accounts/refresh-all`, `/accounts/:id/refresh`, `/accounts/:id/refresh-ig-token`, `/resolve-channel`, `/tracked-content`, `/tracked-content/:id/refresh`, `GET` or `POST /process-scheduled`, `POST /automations/accounts/:accountId/subscribe` | User id | Sliding window log | 30 per 10 minutes |
| `publish` | `POST /accounts/:id/ig-media-publish`, `/accounts/:id/ig-publish` | User id | Leaking bucket | 50 deep, drains 1 every 15 seconds |
+| `mcp` | `POST /mcp`, after `requireMcpAuth` | User id from the access token or OAuth token | Token bucket | Bursts of 60, refills 1 per second |
| `oauth` | `GET /auth/instagram/callback` | Client IP | Fixed window counter | 10 per 10 minutes |
The Instagram webhook (`POST /api/webhooks/instagram`) has only the `ip` rule. Meta sends from its own servers, so a burst past 300 a minute from one of them gets 429, and Meta delivers those notifications again later; nothing is lost. Private replies have their own limits, which are not rate limit rules: hourly counts per instance, user, account and rule and a daily count per person, kept in the database by `reserve_automation_send` so every Worker sees them (`docs/architecture/data-flows/AUTOMATION.md`).
@@ -51,7 +52,7 @@ The client IP comes from `CF-Connecting-IP`, which Cloudflare always sets and wh
| Algorithm | State | How it decides | Why it fits its rule |
|---|---|---|---|
-| Token bucket | Tokens left, last update | Refills `refillPerSecond` tokens up to `capacity`; a request takes one token | Allows page-load bursts, then a steady rate (`user`) |
+| Token bucket | Tokens left, last update | Refills `refillPerSecond` tokens up to `capacity`; a request takes one token | Allows page-load bursts, then a steady rate (`user`); lets an agent chain tool calls without flooding the services (`mcp`) |
| Leaking bucket | Level, last update | The level drains at `leakPerSecond`; a request adds one; a full bucket rejects | Paces a stream evenly (`publish`). The Worker cannot hold requests in a queue, so this is the "leaky bucket as a meter" form: it rejects instead of delaying. |
| Fixed window counter | Window number, count | Counts requests per aligned window | Simple and exact per window, and the boundary burst does not matter at this volume (`oauth`) |
| Sliding window log | Timestamps of accepted requests | Drops timestamps older than the window; accepts while fewer than `limit` remain | Exact in every rolling window, for the rule that protects paid quota (`quota`). Only accepted requests are logged, so the log never exceeds `limit` entries. |
diff --git a/docs/architecture/backend/REQUEST_PIPELINE.md b/docs/architecture/backend/REQUEST_PIPELINE.md
index b065be0..bb5e669 100644
--- a/docs/architecture/backend/REQUEST_PIPELINE.md
+++ b/docs/architecture/backend/REQUEST_PIPELINE.md
@@ -28,6 +28,9 @@ Request
Public routes routes/index.ts /api/health, /api/health/ready, /api/auth/instagram/callback (with its own oauth limit),
/api/auth/email-hook (middleware/authHook.ts checks Supabase's signature),
/api/webhooks/instagram (middleware/metaWebhook.ts checks Meta's signature)
+ MCP endpoint app.ts POST /mcp: middleware/mcpAuth.ts verifies an access token or an approved OAuth
+ client and sets userId, then the mcp limit, then mcpController -> McpService,
+ which runs one tool; each tool calls one service method
6. Authentication middleware/auth.ts verifies the JWT and sets userId; 401 otherwise
7. Per-user limits middleware/rateLimit.ts user, quota and publish rules
8. Route table routes/<feature>Routes.ts
@@ -38,7 +41,7 @@ Request
Response, or a thrown error -> middleware/errorHandler.ts
```
-Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles. The Send Email hook and the Instagram webhook have no user: Supabase Auth and Meta call them, and their signatures take the place of the JWT. The Instagram webhook attaches each comment to the account its signed payload names.
+Authorization is ownership: every user-scoped repository method filters by the verified user id, so another user's row is simply not found (404). There are no roles; the MCP endpoint adds a read or write permission per access token or approved client, checked before any tool runs. The Send Email hook and the Instagram webhook have no user: Supabase Auth and Meta call them, and their signatures take the place of the JWT. The Instagram webhook attaches each comment to the account its signed payload names.
## Request context
diff --git a/docs/architecture/backend/ROUTES.md b/docs/architecture/backend/ROUTES.md
index a9de5de..795b1df 100644
--- a/docs/architecture/backend/ROUTES.md
+++ b/docs/architecture/backend/ROUTES.md
@@ -1,6 +1,6 @@
# Backend Routes
-All routes live under `/api`. Routes in the protected group require a valid Supabase JWT (`requireAuth` middleware). Public routes bypass auth.
+All routes live under `/api`, except the MCP endpoint for Claude clients (see MCP Endpoint). Routes in the protected group require a valid Supabase JWT (`requireAuth` middleware). Public routes bypass auth.
Each route is one line in a route table in `backend/routes/` that points at a controller in `backend/controllers/`; the controller calls one service method. `backend/routes/index.ts` groups the tables into `publicRoutes` and `protectedRoutes`. See `REQUEST_PIPELINE.md` for the layers.
@@ -65,6 +65,18 @@ Supabase Auth calls this route, not a browser, so it has its own rules:
See `docs/architecture/data-flows/AUTHENTICATION.md` for the whole flow.
+## MCP Endpoint
+
+Claude clients reach Twiligent through a Model Context Protocol server registered in `app.ts`, outside `/api`. It has its own credentials and its own error body (JSON-RPC), so the table above does not apply. Tools, sign-in and setup are in `docs/platform-v2/MCP_DOCUMENTATION.md`.
+
+| Method | Path | Controller | Purpose |
+|---|---|---|---|
+| POST | `/mcp` | `mcpController.handleMcpMessage` | One JSON-RPC message in, one JSON reply out (`202` with no body for a notification). Auth by `requireMcpAuth` (`middleware/mcpAuth.ts`): a personal access token (`twl_...`) or a Supabase OAuth token issued to an approved client; an app session token is refused. Rate limited per IP (`ip`) and per user (`mcp`) |
+| GET, DELETE | `/mcp` | `mcpController.refuseMcpStream` | `405` with `Allow: POST`: the server keeps no stream and no session |
+| GET | `/.well-known/oauth-protected-resource`, `/.well-known/oauth-protected-resource/mcp` | `mcpController.getProtectedResourceMetadata` | Protected resource metadata naming Supabase Auth as the authorization server; `404` until `MCP_OAUTH_ENABLED` is `true` |
+
+Statuses on `POST /mcp`: `401` with `WWW-Authenticate: Bearer realm="twiligent"` (plus `resource_metadata` when OAuth is on) for a missing, unknown, revoked or expired credential; `403` for a request from a web page whose `Origin` is not Claude's or the app's, or an OAuth client the person has not approved; `400` for a body that is not JSON-RPC or a header that does not match the body; `404` with `-32601` for an unknown method; `429` from the rate limit. A tool that fails returns `200` with `isError: true` and a message the model can act on.
+
## Protected Routes (require `Authorization: Bearer <jwt>`)
The File column names the route table and the controller.
@@ -176,6 +188,20 @@ Controllers call `AutomationService` (`services/automationService.ts`). Every ro
| GET | `/api/settings/github` | `settingsRoutes.ts`, `settingsController.getGithubSettings` | Retrieve the scheduling repository (`repoOwner`, `repoName`, `branch`) for the current user |
| PUT | `/api/settings/github` | `settingsRoutes.ts`, `settingsController.saveGithubSettings` | Save the scheduling repository; rewrites `settings.github`, dropping any token an older version stored |
+### Claude (MCP access)
+
+Controllers in `mcpAccessController.ts` call `McpAccessService` (`services/mcpAccessService.ts`). The Settings page (Claude section) and the consent page (`/oauth/consent`) use them.
+
+| Method | Path | File | Purpose |
+|---|---|---|---|
+| GET | `/api/mcp/info` | `mcpRoutes.ts`, `mcpAccessController.getMcpInfo` | `{ serverUrl, oauthEnabled }`: the address Claude connects to and whether connector sign-in is on |
+| GET | `/api/mcp/tokens` | `mcpRoutes.ts`, `mcpAccessController.listAccessTokens` | The caller's active access tokens: label, last four characters, permission, last used, expiry. Never the token |
+| POST | `/api/mcp/tokens` | `mcpRoutes.ts`, `mcpAccessController.createAccessToken` | Body `{ label, permission: 'read' \| 'write', expiresInDays: 1-365 \| null }`. `201` with the token, the only response that carries it (`Cache-Control: no-store`); 20 active tokens at most |
+| DELETE | `/api/mcp/tokens/:id` | `mcpRoutes.ts`, `mcpAccessController.revokeAccessToken` | Revokes one of the caller's tokens at once |
+| GET | `/api/mcp/clients` | `mcpRoutes.ts`, `mcpAccessController.listClientGrants` | The OAuth clients the caller approved, with their permission and last use |
+| POST | `/api/mcp/clients` | `mcpRoutes.ts`, `mcpAccessController.approveClient` | Body `{ clientId, clientName, permission }`: saves the consent page's choice for the caller before the page approves the request with Supabase |
+| DELETE | `/api/mcp/clients/:id` | `mcpRoutes.ts`, `mcpAccessController.revokeClient` | Removes an approval; the client is refused at its next call |
+
## Adding a New Route
See `docs/features/NEW_API_ENDPOINT.md` for the complete workflow.
diff --git a/docs/architecture/backend/SERVICES.md b/docs/architecture/backend/SERVICES.md
index 8f00cbb..7c9e7c7 100644
--- a/docs/architecture/backend/SERVICES.md
+++ b/docs/architecture/backend/SERVICES.md
@@ -48,6 +48,8 @@ A service receives only what it uses: repositories, the cleaned `AppConfig` from
| `automationPublicReplies` | `automationPublicReplyProcessor.ts` | public replies | `run({ ids?, subrequests?, timeBudgetMs? })` (post due public replies under their comments; webhook, public reply retry route and every minute cron) |
| `automationReconciler` | `automationReconciler.ts` | comments, public replies | `run()` (expire overdue replies, follow-ups and public replies, look for lost replies on Instagram, log the queue's health; five minute cron, never sends or posts) |
| `retention` | `retentionService.ts` | comments, audit | `purge(now?, { commentBatches? })` (daily cron; comments in batches of 1,000) |
+| `mcpAccess` | `mcpAccessService.ts` | MCP access tokens, MCP client grants, audit | `listTokens`, `createToken`, `revokeToken`, `listClients`, `approveClient`, `revokeClient`, `authenticateToken` and `authorizeClient` (used by `requireMcpAuth`) |
+| `mcpFor(principal)` | `mcpService.ts` | (the other services, through the tools in `backend/mcp/`) | `handle(body, headers)`: one JSON-RPC message for one verified caller; lists only the tools the permission allows, asks for confirmation before publishing or deleting, stops a tool after 25 seconds, refuses a result over 40,000 characters, and audits write tools |
| `health` | `healthService.ts` | health | `readiness()` (`GET /api/health/ready`: one database read, timed; returns no data) |
Every user-scoped method takes the verified `userId` as its first argument. Methods that need one of the user's records load it with a `...ForUser` repository method and throw `NotFoundError` when it is missing or on the wrong platform, so another user's record is never found. `scheduledPublisher`, `tokenRefresh`, `automationWebhook`, `automationProcessor`, `automationFollowups`, `automationPublicReplies`, `automationReconciler` and `retention` are the only services that use the cross-user repository methods (`listByPlatform`, `findById`, `updateById`, `listDue`, `listStale`, `claim`, and the automation queue, follow-up, review, intake and retention methods).
diff --git a/docs/architecture/cloudflare/CI_CD.md b/docs/architecture/cloudflare/CI_CD.md
index 0afa31b..fca9375 100644
--- a/docs/architecture/cloudflare/CI_CD.md
+++ b/docs/architecture/cloudflare/CI_CD.md
@@ -52,7 +52,7 @@ A type error or failing test stops the run before the deploy step.
- `CLOUDFLARE_API_TOKEN` - API token with Worker deploy permission
- `CLOUDFLARE_ACCOUNT_ID` - your Cloudflare account ID
-The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, the optional automation settings `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, `META_APP_SECRET` and `AUTOMATION_*`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.
+The workflow does not set the Worker's own secrets (`SUPABASE_*`, `FRONTEND_URL`, the optional `ALLOWED_ORIGINS`, the optional email secrets `SEND_EMAIL_HOOK_SECRET`, `RESEND_API_KEY`, `EMAIL_FROM` and `EMAIL_DAILY_LIMIT`, the optional automation settings `INSTAGRAM_WEBHOOK_VERIFY_TOKEN`, `META_APP_SECRET` and `AUTOMATION_*`, the optional Claude settings `TOKEN_ENCRYPTION_KEY` and `MCP_OAUTH_ENABLED`, and the rest). They are set once with `npx wrangler secret put` and kept across deploys; see `WORKERS.md`.
**Does not** redeploy on frontend-only changes, documentation changes, or script changes.
diff --git a/docs/architecture/cloudflare/WORKERS.md b/docs/architecture/cloudflare/WORKERS.md
index c7495c9..88e4a6c 100644
--- a/docs/architecture/cloudflare/WORKERS.md
+++ b/docs/architecture/cloudflare/WORKERS.md
@@ -57,6 +57,8 @@ All secrets are set via `npx wrangler secret put <NAME>`, run from `backend/`. T
| `EMAIL_FROM` | Optional | Sender of the auth emails on a domain verified in Resend, such as `Twiligent <[email protected]>` |
| `EMAIL_DAILY_LIMIT` | Optional | Auth emails a day across all users (each code sign-in is one) before the sign-in page pauses email codes and points to Google or a password; defaults to `100`, Resend's free daily quota |
| `INSTAGRAM_WEBHOOK_VERIFY_TOKEN` | Optional | The Verify Token typed into the Meta dashboard's Instagram webhook settings; `GET /api/webhooks/instagram` answers Meta's check only with it. Without it, and `INSTAGRAM_APP_SECRET`, no comment reaches the Worker and the Automations page says so |
+| `TOKEN_ENCRYPTION_KEY` | Optional | At least 32 random characters (`openssl rand -base64 48`). Keys derived from it sign the MCP confirmation tokens, so without it the Claude tools that publish or delete refuse to run; YouTube publishing will also encrypt stored tokens with it. Changing it voids confirmations in flight |
+| `MCP_OAUTH_ENABLED` | Optional | `true` once Supabase Auth's OAuth server is turned on with the authorization path `/oauth/consent`; the MCP endpoint then publishes its protected resource metadata, so Claude on the web, desktop and mobile can connect. Access tokens work without it |
| `META_APP_SECRET` | Optional | The Meta app's own secret (App settings, Basic). Webhook signatures are checked against `INSTAGRAM_APP_SECRET` and, when this is set, against it too |
| `AUTOMATION_PAUSED` | Optional | `true` holds every comment-to-DM reply on the instance; comments are still stored and matched |
| `AUTOMATION_ACCOUNT_HOURLY_LIMIT` | Optional | Private replies an hour per Instagram account; default `200`, at most `750` (Instagram's limit) |
@@ -102,6 +104,8 @@ UPSTASH_REDIS_REST_TOKEN=...
# only to test the Instagram webhook locally; Meta cannot reach localhost, so sign request bodies yourself
# INSTAGRAM_WEBHOOK_VERIFY_TOKEN=a-long-random-string
# AUTOMATION_PAUSED=true
+# signs the MCP confirmation tokens; any 32 or more random characters
+# TOKEN_ENCRYPTION_KEY=...
```
Run locally from the repository root: `npm run dev:backend` (Worker only, port 8787) or `npm run dev` (Worker and Vite together). Both run `wrangler dev` in `backend/`, which reloads on save.
diff --git a/docs/architecture/data-flows/AUTHENTICATION.md b/docs/architecture/data-flows/AUTHENTICATION.md
index a7cc005..80731a5 100644
--- a/docs/architecture/data-flows/AUTHENTICATION.md
+++ b/docs/architecture/data-flows/AUTHENTICATION.md
@@ -17,6 +17,8 @@ When the browser already holds a session, `/login` opens the dashboard (`/`) ins
The public site's home page (`https://twiligent.ujjwal.fyi/`) opens the dashboard too. The site is another origin and cannot read the session, so `AuthProvider` writes the cookie `twiligent_signed_in=1` on the shared domain whenever a session is present and clears it whenever it is not (`signedInCookie()` in `lib/signedInCookie.ts`: `Domain=twiligent.ujjwal.fyi`, 30 days renewed on every load, `SameSite=Lax`, `Secure`). The cookie says only that someone is signed in and carries no token; the API never reads it. It is written only when the app runs under `twiligent.ujjwal.fyi`, so self-hosted and local apps write nothing. See `docs/architecture/site/SITE.md` and ADR-042.
+A protected page opened while signed out sends the person to `/login?next=<path and query>` (`ProtectedRoute` with `signInPathFor()`), and every way of signing in on the page then returns there. `returnPath()` in `lib/signInPage.ts` accepts only a path on this site: anything else (another host, `//host`, `/\host`, a scheme, whitespace or control characters) falls back to `/`. The hash is left behind, since it can carry a one-time code meant for the page. The Claude consent page relies on this.
+
`?mode=signup` (the public site's Get started buttons) keeps the `start` view but shows the headline "Create your Twiligent account" and Google's "Sign up with Google". The default ways to join are Google and an emailed code, both of which create the account on first use; the password sign-up stays behind the password view for instances that do not email codes.
## Login Flow (Emailed Code, the Default)
@@ -228,6 +230,18 @@ Supabase JS client handles token refresh automatically. The access token expires
No manual refresh logic is needed in the frontend.
+## Claude Connector Sign-in (OAuth Consent)
+
+Claude on the web, desktop and mobile signs in to the MCP endpoint through Supabase Auth's OAuth 2.1 server, turned on by the owner (`MCP_OAUTH_ENABLED`; `docs/platform-v2/MCP_DOCUMENTATION.md`).
+
+1. Claude calls `POST /mcp` without a token and gets `401` with `resource_metadata`; the metadata names Supabase Auth as the authorization server. Claude registers itself there and opens Supabase's authorize URL.
+2. Supabase sends the browser to the app's `/oauth/consent?authorization_id=...` (`pages/OAuthConsent.tsx`, outside the app shell). Signed out, `ProtectedRoute` sends it through `/login?next=...` and back.
+3. The page loads the request with `supabase.auth.oauth.getAuthorizationDetails`. If the person approved this client before, Supabase returns a redirect and the page follows it at once. Otherwise it shows the app's name, the site it returns to and the signed-in email, and asks for Read only (chosen by default) or Read and make changes.
+4. Allow saves the choice with `POST /api/mcp/clients` first, then calls `approveAuthorization(..., { skipBrowserRedirect: true })` and goes to the returned address. Deny calls `denyAuthorization`. Either way the page leaves only for an `https` address, or `http` on `localhost`, `127.0.0.1` or `[::1]` (`isSafeRedirect()` in `lib/oauthConsent.ts`).
+5. Claude exchanges the code with Supabase and calls `/mcp` with the access token. `requireMcpAuth` verifies it, reads its `client_id` claim and requires the saved choice; without one the client is refused.
+
+Removing an app in Settings, Claude deletes the saved choice and also calls `supabase.auth.oauth.revokeGrant`, so connecting it again shows the consent page instead of being refused.
+
## Instagram OAuth (Separate Flow)
Instagram OAuth is not user authentication - it is account connection. The flow is documented in the system overview under "Instagram OAuth" and does not use Supabase Auth.
diff --git a/docs/architecture/database/SCHEMA.md b/docs/architecture/database/SCHEMA.md
index 91538d8..168cab1 100644
--- a/docs/architecture/database/SCHEMA.md
+++ b/docs/architecture/database/SCHEMA.md
@@ -406,6 +406,47 @@ One row per message or public reply request sent to Instagram. The private reply
---
+## Claude (MCP) Tables
+
+How Claude clients sign in to the MCP endpoint (`docs/platform-v2/MCP_DOCUMENTATION.md`). Both are read and written only by the Worker with the service key; browser access is revoked like every other table.
+
+### Table: `mcp_access_tokens`
+
+Personal access tokens a person creates in Settings, Claude. The token is shown once; only its hash is kept.
+
+| Column | Type | Constraints | Description |
+|---|---|---|---|
+| `id` | text | primary key | `newRowId()` |
+| `user_id` | uuid | not null, references `auth.users` on delete cascade | |
+| `label` | text | not null, 1 to 80 characters | The person's name for it, such as the computer it is for |
+| `token_hash` | text | not null, unique, 64 lowercase hex characters | SHA-256 of the token (`twl_` and 43 base64url characters from 32 random bytes); a fast hash is enough because the token is random, not a password |
+| `token_hint` | text | not null, 4 characters | The token's last four characters, shown in Settings |
+| `permission` | text | `read` or `write` | Which tools the token may list and run |
+| `last_used_at` | timestamptz | | Written at most once an hour per token |
+| `expires_at` | timestamptz | | Null when the token does not expire; at most 365 days ahead when set |
+| `revoked_at` | timestamptz | | Set on revoke; a revoked token is refused and no longer listed |
+| `created_at`, `updated_at` | timestamptz | not null, default now() | |
+
+A person may have 20 active tokens.
+
+### Table: `mcp_client_grants`
+
+The OAuth clients (Claude's apps) a person approved on the consent page, and what each may do. Supabase Auth issues the client's tokens; this table is Twiligent's own record, and the MCP endpoint refuses a client without a row here.
+
+| Column | Type | Constraints | Description |
+|---|---|---|---|
+| `id` | text | primary key | `newRowId()` |
+| `user_id` | uuid | not null, references `auth.users` on delete cascade | |
+| `client_id` | text | not null, unique with `user_id` | The OAuth client id Supabase Auth issued, the `client_id` claim of its tokens |
+| `client_name` | text | not null, 1 to 200 characters | The name the client registered, shown in Settings |
+| `permission` | text | `read` or `write` | Chosen on the consent page |
+| `last_used_at` | timestamptz | | Written at most once an hour per client |
+| `created_at`, `updated_at` | timestamptz | not null, default now() | |
+
+Approving the same client again updates its row, so its id stays the same.
+
+---
+
## Table: `audit_events`
Who connected, reconnected or removed an account, changed a rule, paused or subscribed an account, or retried a reply. Rows reference only the user, so they outlive the account they describe.
@@ -414,8 +455,8 @@ Who connected, reconnected or removed an account, changed a rule, paused or subs
|---|---|---|---|
| `id` | text | primary key | `newRowId()` |
| `user_id` | uuid | not null, references `auth.users` on delete cascade | |
-| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried`, `automation_public_reply.retried` |
-| `subject_type` | text | `account`, `automation_rule`, `automation_account`, `automation_comment` | |
+| `action` | text | `^[a-z_]+\.[a-z_]+$` | `account.connected`, `account.reconnected`, `account.removed`, `automation_rule.created`, `.updated`, `.duplicated`, `.deleted`, `automation_account.paused`, `.resumed`, `.subscribed`, `automation_comment.retried`, `automation_public_reply.retried`, `mcp_access_token.created`, `.revoked`, `mcp_client.approved`, `.revoked`, and `mcp_access_token.called_tool` or `mcp_client.called_tool` for each write tool a Claude client ran (with the tool name and outcome) |
+| `subject_type` | text | `account`, `automation_rule`, `automation_account`, `automation_comment`, `mcp_access_token`, `mcp_client`, `scheduled_post`, `tracked_post`, `media_asset`, `youtube_connection`, `youtube_upload`, `settings` | The last six are for changes made through Claude clients, publishing, media and YouTube |
| `subject_id` | text | | |
| `details` | jsonb | not null, default `{}`, an object | Small facts such as the platform or the changed field names; never tokens or comment text |
| `created_at`, `updated_at` | timestamptz | not null, default now() | |
@@ -463,6 +504,7 @@ An index exists because a frequent query filters or orders on its columns. Each
| `automation_comments_created_at_idx` | `automation_comments (created_at)` | `purge_automation_comments`: the oldest comments first, a batch at a time | |
| `automation_attempts_*_started_at_idx` | `(started_at)`, `(user_id, started_at)`, `(account_id, started_at)`, `(rule_id, started_at)`, `(account_id, recipient_id, started_at)` | `reserve_automation_send`: sends in the last hour per scope, and per recipient in the last day | One per limit the reservation counts |
| `automation_attempts_comment_idx` | `automation_attempts (automation_comment_id)` | Finishing and recovering one comment's attempt; the cascade | |
+| `mcp_access_tokens_user_created_idx`, `mcp_client_grants_user_created_idx` | `(user_id, created_at desc)` | Listing a person's tokens and approved clients in Settings | The token lookup by hash uses the unique `token_hash` key, and a client lookup the unique `(user_id, client_id)` key |
| `audit_events_user_id_created_at_idx`, `audit_events_created_at_idx` | `(user_id, created_at desc)`, `(created_at)` | Listing a user's events; the retention delete | |
The primary keys serve every lookup by `id`, and `settings` is read through its `(user_id, key)` primary key.
diff --git a/docs/architecture/database/SECURITY.md b/docs/architecture/database/SECURITY.md
index 2535d84..75b4afe 100644
--- a/docs/architecture/database/SECURITY.md
+++ b/docs/architecture/database/SECURITY.md
@@ -4,7 +4,7 @@
The backend uses the **service-role key** for all database operations. This key bypasses Row Level Security (RLS). Data isolation is enforced by the application:
-1. `requireAuth` middleware verifies the JWT and sets `userId` on the Hono context from Supabase's response - this is the only trusted source of `userId`
+1. `requireAuth` middleware (or `requireMcpAuth` on `/mcp`, see Claude (MCP) Access) verifies the JWT and sets `userId` on the Hono context from Supabase's response - this is the only trusted source of `userId`
2. Controllers pass that `userId` to services, and every user-scoped repository method (named `...ForUser`) appends `.eq('user_id', userId)` using this verified value
3. `userId` is never accepted from request body, query params, or any other user-controlled input
@@ -53,7 +53,7 @@ The migrations in `supabase/migrations/` enforce this on every instance:
The service-role key used by the Worker and the GitHub Actions scheduler bypasses row level security and keeps its grants. The frontend never queries tables directly (it uses Supabase only for Auth). `backend/tests/database/migrations.test.ts` fails if a migration creates a function without the revoke.
-To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all eleven tables and for `POST /rest/v1/rpc/merge_account_data`, `POST /rest/v1/rpc/claim_automation_comments`, `POST /rest/v1/rpc/claim_automation_followups` and `POST /rest/v1/rpc/claim_automation_public_replies`. The manual check is in `docs/workflows/TESTING.md`.
+To check a live instance, call the Data API with the anon key (`GET <SUPABASE_URL>/rest/v1/accounts` with the `apikey` header): it must answer 401 for all thirteen tables and for `POST /rest/v1/rpc/merge_account_data`, `POST /rest/v1/rpc/claim_automation_comments`, `POST /rest/v1/rpc/claim_automation_followups` and `POST /rest/v1/rpc/claim_automation_public_replies`. The manual check is in `docs/workflows/TESTING.md`.
### What was wrong before
@@ -92,6 +92,15 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live
`POST /api/webhooks/instagram` is public: Meta calls it without a user. `middleware/metaWebhook.ts` refuses a body over 1 MB and checks `X-Hub-Signature-256`, an HMAC-SHA256 of the raw body with the Instagram app secret (or `META_APP_SECRET`), in constant time before anything is parsed or stored. The verification `GET` compares the Verify Token in constant time. A comment is attached to an account only through the Instagram account id Meta signed, and only accounts with an enabled rule store anything. Comments that no rule answers keep neither their text nor their author; matched ones are kept 90 days. Logs carry ids and error codes, never tokens or comment text.
+## Claude (MCP) Access
+
+The MCP endpoint (`POST /mcp`) does not take the app's session token. `requireMcpAuth` sets the same verified `userId` from one of two credentials, and every tool then calls the same user-scoped services as the API:
+
+- **Personal access tokens.** `twl_` plus 32 random bytes, shown once. Only the SHA-256 hash is stored (`mcp_access_tokens.token_hash`), so a database leak does not reveal usable tokens. `mcpAccessTokenRepository.findActiveByHash` and `markUsed` are its only methods that are not user-scoped: the first turns a presented token into its owner, the second records the use on the row just found, and only `requireMcpAuth` reaches them. Revoking sets `revoked_at`, which takes effect on the next request.
+- **OAuth clients.** Supabase Auth's OAuth server issues the token; the Worker checks it with `auth.getUser` and requires a `client_id` claim plus a row in `mcp_client_grants` for that user and client, written by the consent page. Removing the row stops the client at its next call even while its token is valid.
+
+Each credential carries `read` or `write`. A read credential never sees the write tools in `tools/list` and is refused if it calls one. Publishing and deleting also need a confirmation token: an HMAC over the user, the tool and the exact arguments, keyed from `TOKEN_ENCRYPTION_KEY`, valid for five minutes. Every write tool call is recorded in `audit_events`.
+
## Audit Events
`audit_events` records connecting, reconnecting and removing accounts, rule changes, pausing and subscribing an account, and retries, with the user, the subject and small details (never tokens or comment text). Rows reference the user only, so they stay after the account is removed, and are deleted after a year or with the user.
@@ -104,6 +113,8 @@ The Instagram `accessToken` stored in `accounts.data.accessToken` is a long-live
When reviewing security, check these files:
- `backend/middleware/auth.ts` - JWT verification
+- `backend/middleware/mcpAuth.ts` and `backend/services/mcpAccessService.ts` - the only things that authenticate `/mcp`; `findActiveByHash` is their one unscoped lookup
+- `backend/services/mcpService.ts` and `backend/mcp/tools/` - each tool takes the user from `principal.userId`, never from its arguments, and checks its permission before running
- `backend/repositories/` - every user-scoped method ends in `ForUser` and filters by `user_id` (or passes it as `p_user_id` to a merge function); the methods without a `userId` are used only by `scheduledPublisher.ts`, `tokenRefreshService.ts`, `automationWebhookService.ts`, `automationProcessor.ts`, `automationFollowupProcessor.ts`, `automationPublicReplyProcessor.ts`, `automationReconciler.ts` and `retentionService.ts`. `automationPublicReplyRepository.ts` follows the same split: `requeueForUser` and `releaseHeldForAccount` take the verified user, the claim, reservation, finish and review methods serve the dispatch and the reconcile. `emailQuotaRepository.ts` is not user-scoped: it keeps instance-wide Redis counters for the Send Email hook, keyed by a hash of the address. `healthRepository.ts` is not user-scoped either: its one read proves the database answers and its result is discarded
- `backend/middleware/authHook.ts` and `backend/lib/webhookSignature.ts` - the only thing that authenticates the public Send Email hook
- `backend/middleware/metaWebhook.ts` and `backend/lib/metaWebhookSignature.ts` - the only thing that authenticates the public Instagram webhook
diff --git a/docs/architecture/frontend/API_LAYER.md b/docs/architecture/frontend/API_LAYER.md
index 01b8167..65692db 100644
--- a/docs/architecture/frontend/API_LAYER.md
+++ b/docs/architecture/frontend/API_LAYER.md
@@ -146,6 +146,20 @@ subscribeAutomationAccount: (accountId: string) => request<AutomationAccountResp
The types are in `shared/types/automation.ts`. Activity and stats take their filters as `URLSearchParams` (`accountId`, `ruleId`, `status` as a comma-separated list, `from`, `to`, `before`, `limit`), built in `features/automations/useAutomationActivity.ts`. An accepted reply means Instagram took the request; the API reports nothing about delivery or reading. Rules carry `matchMode` (`contains`, `exact` or `any`) and the followers-only fields `requireFollow`, `followPromptText` and `notFollowingText`; account states carry `limitedUntil` and `messagesSubscribed`; activity items carry `gateStatus` and `followup`.
+## Claude (MCP) Methods
+
+```ts
+getMcpInfo: () => request<McpServerInfoResponse>('/mcp/info'),
+getMcpTokens: () => request<McpAccessTokenListResponse>('/mcp/tokens'),
+createMcpToken: (data: McpAccessTokenCreateRequest) => request<McpAccessTokenCreateResponse>('/mcp/tokens', { method: 'POST', body: JSON.stringify(data) }),
+revokeMcpToken: (id: string) => request<SuccessResponse>(`/mcp/tokens/${id}`, { method: 'DELETE' }),
+getMcpClients: () => request<McpClientGrantListResponse>('/mcp/clients'),
+approveMcpClient: (data: McpClientApprovalRequest) => request<SuccessResponse>('/mcp/clients', { method: 'POST', body: JSON.stringify(data) }),
+revokeMcpClient: (id: string) => request<SuccessResponse>(`/mcp/clients/${id}`, { method: 'DELETE' }),
+```
+
+The types are in `shared/types/mcp.ts`. Settings, Claude (`features/settings/useClaudeAccess.ts`) uses all but `approveMcpClient`, which the consent page (`pages/useOAuthConsent.ts`) calls before it approves the request with `supabase.auth.oauth.approveAuthorization`. The token from `createMcpToken` is kept only in component state until the person dismisses it. These calls manage access; the MCP endpoint itself (`/mcp`) is never called from the app.
+
## Tracked Content Methods
Added to the `api` object in `api.ts`. Tracked content is YouTube videos only:
diff --git a/docs/architecture/frontend/FEATURES.md b/docs/architecture/frontend/FEATURES.md
index 40916d8..636f983 100644
--- a/docs/architecture/frontend/FEATURES.md
+++ b/docs/architecture/frontend/FEATURES.md
@@ -93,6 +93,10 @@ frontend/src/
│ │ ├── SchedulingSetupSteps.tsx, SetupStep.tsx, GithubRepoForm.tsx, CopyChip.tsx, GuideLinkButton.tsx, RepoLinkButton.tsx
│ │ ├── useServerSettings.ts <- Loads keys and the saved repository; saves the repository
│ │ ├── useApiHealthCheck.ts <- Runs api.health() for the server keys section
+│ │ ├── ClaudeSection.tsx <- Settings, Claude: server address, Claude Code command, tokens, approved apps
+│ │ ├── ClaudeTokenForm.tsx, ClaudeTokenList.tsx, ClaudeClientList.tsx, CopyField.tsx
+│ │ ├── useClaudeAccess.ts <- Loads the address, tokens and apps; creates and revokes tokens; removes apps
+│ │ ├── claudeAccessData.ts <- Pure load sequence, permission and expiry choices, the Claude Code command (claudeAccessData.test.ts)
│ │ ├── settingsData.ts <- Pure load sequence (api injected), links, health text (settingsData.test.ts)
│ │ └── schedulingProgress.ts <- Pure guide progress in localStorage (schedulingProgress.test.ts)
│ ├── analytics/videos/
diff --git a/docs/architecture/frontend/ROUTING.md b/docs/architecture/frontend/ROUTING.md
index f3643c0..4fdb946 100644
--- a/docs/architecture/frontend/ROUTING.md
+++ b/docs/architecture/frontend/ROUTING.md
@@ -9,8 +9,9 @@ The app uses React Router 7 in `frontend/src/App.tsx`: a data router from `creat
| Path | Component | Notes |
|---|---|---|
| `/login` | `Login.tsx` | Public - redirects to `/` if already authenticated. Opens on the start view: Continue with Google, an email field that sends a sign-in code, and a Use password link. `?mode=signup` keeps the same view with the headline "Create your Twiligent account" and Google's "Sign up with Google"; the emailed code creates the account the first time an address is used (the public site's Get started buttons link to `https://app.twiligent.ujjwal.fyi/login?mode=signup`) |
+| `/oauth/consent` | `pages/OAuthConsent.tsx` | Protected, outside the app shell: Supabase Auth's OAuth server sends a person here to approve a Claude app (`?authorization_id=`). Signed out, it signs in through `/login?next=...` and comes back. See `docs/architecture/data-flows/AUTHENTICATION.md` |
| `/docs/*` | `components/DocsRedirect.tsx` | Public. The docs live on the public site; this route replaces the location with the same path and hash under `https://twiligent.ujjwal.fyi/docs` (`docsUrl()` in `lib/docs.ts`), so old links keep working |
-| `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login` if unauthenticated |
+| `/` (layout) | `AppLayout` (inline) | Protected - redirects to `/login?next=<path>` if unauthenticated, and back after sign-in |
| `/` (index) | `Overview.tsx` | Default page after login |
| `/accounts` | `AccountManager.tsx` | Connect and remove accounts. `?add=1` opens the add flow; Instagram sign-in returns `#ig_code=...&ig_state=...` in the fragment, which the page removes from the address and posts to `api.completeInstagramConnection` (the server connects the account only for the person who started the sign-in), or `?ig_error` when it failed or was cancelled |
| `/channel/:id` | `ChannelAnalytics.tsx` | `:id` = account.id for YouTube accounts |
@@ -31,7 +32,7 @@ The app uses React Router 7 in `frontend/src/App.tsx`: a data router from `creat
## Auth Guard
-Auth protection is applied via a `<ProtectedRoute>` component wrapping the layout route in `App.tsx`. All child routes are protected. `/login` and `/docs/*` (the redirect to the public docs) are the only public routes.
+Auth protection is applied via a `<ProtectedRoute>` component wrapping the layout route and `/oauth/consent` in `App.tsx`. All child routes are protected. A signed-out visit keeps the path and query in `next`, and `returnPath()` in `lib/signInPage.ts` accepts only a path on this site. `/login` and `/docs/*` (the redirect to the public docs) are the only public routes.
## Lazy Loading
diff --git a/docs/platform-v2/MCP_DOCUMENTATION.md b/docs/platform-v2/MCP_DOCUMENTATION.md
index f2d15a4..9ad2cf3 100644
--- a/docs/platform-v2/MCP_DOCUMENTATION.md
+++ b/docs/platform-v2/MCP_DOCUMENTATION.md
@@ -117,6 +117,12 @@ Every tool works only on the caller's own data. Read tools need no confirmation.
| Tool | Kind | Input | Result |
|---|---|---|---|
+| `list_accounts` | read | none | `accounts`: id, platform, name, handle, headline figures (never a token) |
+| `get_youtube_channel_analytics` | read | `accountId` | `channel` figures and growth estimates, `uploads` averages and engagement, the best, worst and most recent `videos` |
+| `list_youtube_videos` | read | `accountId`, `sort` (`recent` or `views`), `limit`, `cursor` | `videos`, `nextCursor`, `total`, `fetchedAt` |
+| `compare_youtube_channels` | read | none | `channels`, combined `totals`, the `leaders` by subscribers, views and videos |
+| `get_instagram_account_analytics` | read | `accountId` | `account` figures, `posts` averages and engagement rate, `byContentType`, `postFrequency`, the best and worst posts |
+| `list_instagram_media` | read | `accountId`, `limit`, `cursor` | `posts` (captions cut at 300 characters, with a permalink), `nextCursor`, `total`, `fetchedAt` |
| `get_settings` | read | none | Which server keys are set (never their values); the GitHub repository setting |
| `get_instagram_publishing_limit` | read | `accountId` | Posts published in the last 24 hours and the limit |
| `update_github_settings` | write | `repoOwner`, `repoName`, `branch` | The saved setting |
diff --git a/docs/workflows/DEPLOYMENT.md b/docs/workflows/DEPLOYMENT.md
index 13d9f33..b130e52 100644
--- a/docs/workflows/DEPLOYMENT.md
+++ b/docs/workflows/DEPLOYMENT.md
@@ -144,6 +144,8 @@ npx wrangler secret put EMAIL_DAILY_LIMIT # optional; defaults to 100
npx wrangler secret put INSTAGRAM_WEBHOOK_VERIFY_TOKEN # optional; comment-to-DM automation (with INSTAGRAM_APP_SECRET)
npx wrangler secret put META_APP_SECRET # optional; a second key for webhook signatures
npx wrangler secret put AUTOMATION_PAUSED # optional; "true" holds every automated reply
+npx wrangler secret put TOKEN_ENCRYPTION_KEY # optional; signs MCP confirmations (openssl rand -base64 48)
+npx wrangler secret put MCP_OAUTH_ENABLED # optional; "true" after turning on Supabase's OAuth server
```
The `AUTOMATION_*` limits (`ACCOUNT_HOURLY_LIMIT`, `USER_HOURLY_LIMIT`, `GLOBAL_HOURLY_LIMIT`, `RECIPIENT_DAILY_LIMIT`, `PUBLIC_ACCOUNT_HOURLY_LIMIT`, `BATCH_SIZE`) are optional too; `WORKERS.md` lists their defaults.
diff --git a/docs/workflows/TESTING.md b/docs/workflows/TESTING.md
index 7c09132..f47134c 100644
--- a/docs/workflows/TESTING.md
+++ b/docs/workflows/TESTING.md
@@ -28,6 +28,7 @@ Tests never sit next to source files. Each workspace has a `tests/` folder that
| `backend/routes/settingsRoutes.ts` | `backend/tests/routes/settingsRoutes.test.ts` |
| `backend/services/scheduledPublisher.ts` | `backend/tests/services/scheduledPublisher.test.ts` |
| `backend/lib/scheduledPublishing.ts` | `backend/tests/lib/scheduledPublishing.test.ts` |
+| `backend/mcp/tools/analyticsTools.ts` | `backend/tests/mcp/analyticsTools.test.ts` |
| `backend/repositories/scheduledPostRepository.ts` | `backend/tests/repositories/scheduledPostRepository.test.ts` |
| `backend/services/tokenRefreshService.ts` | `backend/tests/services/tokenRefreshService.test.ts` |
| `backend/repositories/accountRepository.ts` | `backend/tests/repositories/accountRepository.test.ts` |
@@ -97,6 +98,8 @@ The database migrations have their own test. `tests/database/migrations.test.ts`
Comment automation has its own tests. `tests/lib/automationMatching.test.ts` covers whole-word and exact matching, case, look-alike characters, literal punctuation in keywords, and that a comment on one reel never triggers a rule for another. `tests/lib/automationDelivery.test.ts` covers the Graph error classes, backoff with jitter, the cooldown from Meta's usage header, and what is recorded for each answer: accepted, rate limited, blocked, temporary errors up to the fifth try, already replied, a refused token (held), not allowed, no answer (needs review), and a request the runtime refused (not sent). `tests/lib/metaWebhookSignature.test.ts` checks signatures with either secret, changed bodies and malformed headers. `tests/fixtures/fakeAutomationQueue.ts` is an in-memory twin of the claim, reserve and finish functions, following the SQL's rules, and `tests/services/automationProcessor.test.ts` runs the processor against it: two comments at once, three reels with their own rules, two runs competing for the same jobs (each reply sent once), a burst over the batch and per-account fairness, a timeout that is never resent, a run that stopped before and during a send, a rate limit cooling one account while another keeps sending, the hourly and per-person limits, five temporary failures, a rule turned off, a deleted reel, an expired comment, a refused token holding the account, the instance pause, a database failure on one job and on the claim, a cancelled run and one without time for a whole send handing their jobs back unstarted, and a run claiming only what its subrequests pay for. `tests/services/automationWebhookService.test.ts` covers intake: per-reel matching, unmatched comments kept without words, own comments, duplicates within and across notifications, accounts without rules, a failed insert, and the verify token. `tests/repositories/automationCommentRepository.test.ts` pages through comments stored in the same instant without skipping or repeating one, and checks the hand-back of unstarted jobs. `tests/routes/instagramWebhookRoutes.test.ts` runs the public route end to end (challenge, signed comment stored then answered, duplicates, either secret, bad signatures, bad bodies, the 1 MB limit, a missing secret, a database failure), and `tests/routes/automationRoutes.test.ts` the user routes, including every route answering 404 for another user's rule, account or item. `tests/fixtures/metaWebhook.ts` signs notifications the way Meta does. `fakeAutomationQueue.ts` also mirrors the turn-taking claim, follow-ups, expiry and review. `tests/services/automationFollowupProcessor.test.ts` covers followers-only replies: a follower gets the link, someone not following gets a reminder and the second ends the wait, nothing is sent when Instagram cannot say, a lost answer needs review and is never sent again, and two runs at once send each follow-up once. `tests/services/automationReconciler.test.ts` covers a lost reply found in the conversation (accepted, nothing sent) or not found (left for a person), and the expiry and health warning. `tests/lib/automationRules.test.ts`, `automationReview.test.ts` and `automationHealth.test.ts` cover the rule checks, matching a lost reply by its digest and time, and the warning line; `tests/services/instagram/instagramMessaging.test.ts` the send, follow check, conversation read and subscription requests; `tests/repositories/automationFollowupRepository.test.ts` the follow-up database calls. Public replies (ADR-044): `tests/lib/automationPublicReply.test.ts` covers the stable wording per comment, the text bounds, what is recorded for each answer (posted only with an id, a lost answer for review, a deleted comment skipped, a public-only cooldown and a day-long block, retries, a held account, expiry) and when a lost reply goes out again. `tests/services/automationPublicReplyProcessor.test.ts` runs the public processor against the fake queue: posting with the stored text while the private reply is left alone, a failed private reply never repeating the public one and a public retry never repeating the private one, a lost answer never posted again by the dispatch, two runs at once posting each reply once, a rate limit cooling public replies only, one public reply per person and post, the account's hourly limit, a public reply turned off, an interrupted run and the instance pause. `tests/services/automationReconciler.test.ts` also covers a lost public reply found on the second page of replies, sent again once after two full reads, never sent again with a page unread or after a second lost answer, and a read Instagram refuses. `tests/services/instagram/instagramComments.test.ts` covers the reply request, answers without an id, refusals and paging; `tests/routes/instagramWebhookRoutes.test.ts` a rule with both replies end to end, where the private reply fails, the public one is posted and a redelivery sends neither again; `tests/routes/automationRoutes.test.ts` the public reply retry, the refused private retry of a public-only comment, and public-only rules. The SQL functions cannot run in Node; they were checked on a local Postgres (PGlite, and Postgres 18 for the public reply functions, including eight claims at once on 10,000 waiting replies with no reply claimed twice) before the first push: deduplication, fair claims and lease recovery, each limit, pause and cooldown, a late answer for an interrupted send, stats, cascades, browser access and every rollback.
+The MCP server has its own tests. `tests/lib/mcp/protocol.test.ts` covers parsing JSON-RPC, the two protocol eras, the header checks and the error replies; `tests/lib/mcp/accessToken.test.ts` and `confirmation.test.ts` the token format and hash, and that a confirmation fails for other arguments, another tool, another person or after five minutes. `tests/services/mcpAccessService.test.ts` covers creating, listing, revoking and authenticating tokens and approving clients; `tests/services/mcpService.test.ts` the dispatch, that read-only callers never see or run write tools, the confirmation flow, the timeout, the result size cap and the audit lines. `tests/mcp/scheduledPostTools.test.ts` and `tests/mcp/analyticsTools.test.ts` check each tool's input checks, paging and that another person's records are not found and tokens never appear; `tests/routes/mcpRoutes.test.ts` runs `/mcp` and `/api/mcp/*` in the full app (401 with the challenge, the Origin check, 405 for GET, revoked tokens). On the frontend, `tests/features/settings/claudeAccessData.test.ts` covers the Settings section's helpers, `tests/lib/oauthConsent.test.ts` which return addresses the consent page accepts, and `tests/lib/signInPage.test.ts` that signing in returns only to a path on this site.
+
The Send Email hook has its own tests: `tests/lib/webhookSignature.test.ts` (valid, tampered, wrong-key, multi-signature and replayed requests), `tests/validators/authHookValidators.test.ts`, `tests/services/email/authEmails.test.ts` (the email for each action, the verify links, HTML escaping and the two Secure Email Change emails), `tests/repositories/emailQuotaRepository.test.ts` (daily and per-address caps, hashed keys, Redis failures), `tests/services/authEmailService.test.ts` (Resend requests, idempotency keys, the caps and Resend's own quota errors, skipped notices) and `tests/routes/authHookRoutes.test.ts` (the hook error shape, and the route answering unsigned calls with 401 in the full app). `tests/fixtures/authHook.ts` signs requests the way Supabase Auth does. The Lua claim script cannot run in Node; the repository test runs the same rules in memory. On the frontend, `tests/lib/authErrors.test.ts` covers when the sign-in page shows the daily cap warning and whether it offers Google, `tests/lib/emailAddress.test.ts` when an address looks complete enough to enable the Continue arrow, `tests/lib/googleIdentity.test.ts` the label drawn on the Google button for each text option, and `tests/lib/signInPage.test.ts` when the sign-in page opens the dashboard for a stored session and when it leaves a sign-in on the page to finish.
The testing workflow documented here describes what should run before shipping any change.
@@ -274,6 +277,18 @@ Open the app in a browser. For each changed area, test:
- [ ] A pending post with `attempts` above 0 shows "Trying again on the next run" under its status
- [ ] Deleting or editing a post while it is `publishing` is refused with "Cannot delete a post that is currently publishing" or "Can only edit pending posts"
+**Claude (MCP) (if `/mcp`, the tools, Settings, Claude or the consent page changed):**
+
+- [ ] Settings, Claude shows the server address and the Claude Code command, each with a Copy button that copies it
+- [ ] Create token with no name -> "Give the token a name" under the field; with a name -> the token and the command with it appear once, focus moves to the token, and the list shows it as Read only with its last four characters
+- [ ] `claude mcp add --transport http twiligent <server address> --header "Authorization: Bearer <token>"`, then in Claude Code ask for your accounts -> `list_accounts` answers with your accounts only
+- [ ] With a Read only token, Claude lists no scheduling tools; with Read and make changes, scheduling a post asks for confirmation first and only the confirmed call schedules it
+- [ ] Revoke the token -> the next tool call fails with "This access token is not valid"
+- [ ] `curl -i -X POST <server address> -d '{}'` -> 401 with `WWW-Authenticate: Bearer realm="twiligent"`; `curl -i <server address>` -> 405; the same POST with `-H "Origin: https://evil.example"` -> 403
+- [ ] With `MCP_OAUTH_ENABLED=true` and Supabase's OAuth server on: add a custom connector in Claude with the server address -> signed out, the consent page signs you in first and comes back -> it names the app and `claude.ai`, Read only is chosen -> Allow returns to Claude, and Settings, Claude lists the app under Approved apps
+- [ ] Deny on the consent page returns to Claude without access; Remove in Approved apps -> the app's next call is refused, and connecting again shows the consent page
+- [ ] `/oauth/consent` without `authorization_id` -> "Claude could not be connected" with what to do
+
**Public site and docs (if `site/` or the app's docs links changed):**
Run `npm run dev:site`, or `npm run build --workspace site` and `npm run preview --workspace site` to check the production build.