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.

feat(mcp): serve POST /mcp with its own sign-in and token management

spacesdrive7f74b7422994
diff --git a/backend/app.ts b/backend/app.ts
index 1235762..1aa6df1 100644
--- a/backend/app.ts
+++ b/backend/app.ts
@@ -6,6 +6,8 @@ import { securityHeaders } from './middleware/securityHeaders.ts';
import { injectClients } from './middleware/clients.ts';
import { rateLimit, clientIp, userKey } from './middleware/rateLimit.ts';
import { requireAuth } from './middleware/auth.ts';
+import { requireMcpAuth } from './middleware/mcpAuth.ts';
+import { getProtectedResourceMetadata, handleMcpMessage, refuseMcpStream } from './controllers/mcpController.ts';
import { errorHandler, notFoundHandler } from './middleware/errorHandler.ts';
import { RATE_LIMIT_RULES, QUOTA_ROUTES, PUBLISH_ROUTES, matchesRoute } from './lib/rateLimit/rules.ts';
import { publicRoutes, protectedRoutes } from './routes/index.ts';
@@ -28,6 +30,14 @@ export function createApp(): Hono<AppEnv> {
app.use('*', injectClients);
// 5. limit per network before authentication, so a flood of bad tokens never reaches Supabase Auth
app.use('/api/*', rateLimit(RATE_LIMIT_RULES.ip, clientIp));
+ app.use('/mcp', rateLimit(RATE_LIMIT_RULES.ip, clientIp));
+
+ // the MCP endpoint for Claude clients: its own credentials (an access token or an approved OAuth client), then a
+ // per-user limit; the metadata says where Claude's apps sign in
+ app.get('/.well-known/oauth-protected-resource', ...getProtectedResourceMetadata);
+ app.get('/.well-known/oauth-protected-resource/mcp', ...getProtectedResourceMetadata);
+ app.post('/mcp', requireMcpAuth, rateLimit(RATE_LIMIT_RULES.mcp, userKey), ...handleMcpMessage);
+ app.on(['GET', 'DELETE'], '/mcp', ...refuseMcpStream);
// registered before the protected group, so these answer without authentication
app.route('/api', publicRoutes);
diff --git a/backend/controllers/mcpAccessController.ts b/backend/controllers/mcpAccessController.ts
new file mode 100644
index 0000000..1101d36
--- /dev/null
+++ b/backend/controllers/mcpAccessController.ts
@@ -0,0 +1,46 @@
+import { controller, pathParam, servicesFor } from './http.ts';
+import { jsonBody } from '../middleware/validate.ts';
+import { readConfig } from '../lib/config.ts';
+import { parseAccessTokenCreate, parseClientApproval } from '../validators/mcpValidators.ts';
+import type {
+ McpAccessTokenCreateResponse, McpAccessTokenListResponse, McpClientGrantListResponse, McpServerInfoResponse,
+} from '../../shared/types/mcp.ts';
+import type { SuccessResponse } from '../../shared/types/domain.ts';
+
+export const getMcpInfo = controller.createHandlers(c => {
+ const { mcp } = readConfig(c.env);
+ return c.json({ success: true, serverUrl: mcp.serverUrl, oauthEnabled: mcp.oauthEnabled } satisfies McpServerInfoResponse);
+});
+
+export const listAccessTokens = controller.createHandlers(async c => {
+ const tokens = await servicesFor(c).mcpAccess.listTokens(c.get('userId'));
+ return c.json({ success: true, tokens } satisfies McpAccessTokenListResponse);
+});
+
+export const createAccessToken = controller.createHandlers(jsonBody(parseAccessTokenCreate), async c => {
+ const { token, summary } = await servicesFor(c).mcpAccess.createToken(c.get('userId'), c.req.valid('json'));
+ // the only time the token is sent; no cache or proxy may keep it
+ c.header('Cache-Control', 'no-store');
+ return c.json({ success: true, token, summary } satisfies McpAccessTokenCreateResponse, 201);
+});
+
+export const revokeAccessToken = controller.createHandlers(async c => {
+ await servicesFor(c).mcpAccess.revokeToken(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true } satisfies SuccessResponse);
+});
+
+export const listClientGrants = controller.createHandlers(async c => {
+ const clients = await servicesFor(c).mcpAccess.listClients(c.get('userId'));
+ return c.json({ success: true, clients } satisfies McpClientGrantListResponse);
+});
+
+// the consent page saves the person's choice before it approves the client with Supabase Auth
+export const approveClient = controller.createHandlers(jsonBody(parseClientApproval), async c => {
+ await servicesFor(c).mcpAccess.approveClient(c.get('userId'), c.req.valid('json'));
+ return c.json({ success: true } satisfies SuccessResponse);
+});
+
+export const revokeClient = controller.createHandlers(async c => {
+ await servicesFor(c).mcpAccess.revokeClient(c.get('userId'), pathParam(c, 'id'));
+ return c.json({ success: true } satisfies SuccessResponse);
+});
diff --git a/backend/controllers/mcpController.ts b/backend/controllers/mcpController.ts
new file mode 100644
index 0000000..c5568fb
--- /dev/null
+++ b/backend/controllers/mcpController.ts
@@ -0,0 +1,40 @@
+import { controller, servicesFor } from './http.ts';
+import { readConfig } from '../lib/config.ts';
+import { RPC_ERROR, errorReply } from '../lib/mcp/protocol.ts';
+import type { ContentfulStatusCode } from 'hono/utils/http-status';
+
+// POST /mcp: one JSON-RPC message in, one JSON reply out, for the caller requireMcpAuth verified
+export const handleMcpMessage = controller.createHandlers(async c => {
+ let body: unknown;
+ try {
+ body = await c.req.json();
+ } catch {
+ const reply = errorReply(null, RPC_ERROR.parse, 'The request body is not valid JSON.', 400);
+ return c.json(reply.body, 400);
+ }
+ const reply = await servicesFor(c).mcpFor(c.get('mcpPrincipal')).handle(body, {
+ protocolVersion: c.req.header('MCP-Protocol-Version'),
+ method: c.req.header('Mcp-Method'),
+ name: c.req.header('Mcp-Name'),
+ });
+ if (reply.body === null) return c.body(null, 202);
+ return c.json(reply.body, reply.status as ContentfulStatusCode);
+});
+
+// GET and DELETE /mcp: this server keeps no stream and no session, which the transport answers with 405
+export const refuseMcpStream = controller.createHandlers(c => {
+ c.header('Allow', 'POST');
+ return c.json(errorReply(null, RPC_ERROR.invalidRequest, 'This MCP server takes POST requests only; it keeps no stream or session.', 405).body, 405);
+});
+
+// GET /.well-known/oauth-protected-resource(/mcp): tells Claude's apps where to sign in, once OAuth is turned on
+export const getProtectedResourceMetadata = controller.createHandlers(c => {
+ const { mcp } = readConfig(c.env);
+ if (!mcp.oauthEnabled) return c.json({ error: 'not_found', error_description: 'OAuth sign-in is not turned on for this server; use an access token.' }, 404);
+ return c.json({
+ resource: mcp.serverUrl,
+ authorization_servers: [mcp.authorizationServer],
+ bearer_methods_supported: ['header'],
+ resource_name: 'Twiligent',
+ });
+});
diff --git a/backend/lib/jwtClaims.ts b/backend/lib/jwtClaims.ts
new file mode 100644
index 0000000..bc5fb01
--- /dev/null
+++ b/backend/lib/jwtClaims.ts
@@ -0,0 +1,19 @@
+// reads the claims of a JWT whose signature Supabase Auth has already verified; never use it to trust an unchecked token
+export function jwtClaims(token: string): Record<string, unknown> | null {
+ const payload = token.split('.')[1];
+ if (!payload) return null;
+ try {
+ const json = new TextDecoder().decode(Uint8Array.from(atob(payload.replace(/-/g, '+').replace(/_/g, '/')), char => char.charCodeAt(0)));
+ const claims: unknown = JSON.parse(json);
+ return typeof claims === 'object' && claims !== null && !Array.isArray(claims) ? claims as Record<string, unknown> : null;
+ } catch {
+ // not base64url JSON, so it is not a token Supabase issued
+ return null;
+ }
+}
+
+// OAuth access tokens from Supabase Auth's OAuth server name the client; an app session token has no client_id
+export function oauthClientId(claims: Record<string, unknown> | null): string | null {
+ const clientId = claims?.client_id;
+ return typeof clientId === 'string' && clientId !== '' ? clientId : null;
+}
diff --git a/backend/lib/rateLimit/rules.ts b/backend/lib/rateLimit/rules.ts
index 115f606..9c96c51 100644
--- a/backend/lib/rateLimit/rules.ts
+++ b/backend/lib/rateLimit/rules.ts
@@ -29,6 +29,12 @@ export const RATE_LIMIT_RULES = {
label: 'Too many publishing requests',
config: { algorithm: 'leakingBucket', capacity: 50, leakPerSecond: 1 / 15 },
},
+ // calls from Claude clients to /mcp, per user: an agent may chain many tool calls, but never flood the services
+ mcp: {
+ name: 'mcp',
+ label: 'Too many requests from Claude',
+ config: { algorithm: 'tokenBucket', capacity: 60, refillPerSecond: 1 },
+ },
// the public OAuth callback, per IP
oauth: {
name: 'oauth',
diff --git a/backend/middleware/mcpAuth.ts b/backend/middleware/mcpAuth.ts
new file mode 100644
index 0000000..c84abd9
--- /dev/null
+++ b/backend/middleware/mcpAuth.ts
@@ -0,0 +1,59 @@
+import type { Next } from 'hono';
+import { getSupabaseAuth } from '../database/supabase.ts';
+import { servicesFor } from '../controllers/http.ts';
+import { AppError } from '../lib/errors.ts';
+import { readConfig } from '../lib/config.ts';
+import { isAccessToken } from '../lib/mcp/accessToken.ts';
+import { jwtClaims, oauthClientId } from '../lib/jwtClaims.ts';
+import { RPC_ERROR } from '../lib/mcp/protocol.ts';
+import type { McpPrincipal } from '../services/mcpAccessService.ts';
+import type { AppContext } from '../types/app.ts';
+
+const BEARER = /^Bearer\s+(\S+)$/i;
+// Claude's apps connect from Anthropic's servers; a browser page on any other site must not reach the endpoint
+const CLAUDE_ORIGINS = ['https://claude.ai', 'https://claude.com'];
+// the error code the spec leaves to servers for an authentication failure inside a JSON-RPC body
+const AUTH_ERROR_CODE = -32001;
+
+function failure(c: AppContext, status: 401 | 403, message: string): Response {
+ const config = readConfig(c.env).mcp;
+ if (status === 401) {
+ // the challenge starts OAuth sign-in in Claude's apps once the owner has turned it on
+ const metadata = config.oauthEnabled ? `, resource_metadata="${config.resourceMetadataUrl}"` : '';
+ c.header('WWW-Authenticate', `Bearer realm="twiligent"${metadata}`);
+ }
+ return c.json({ jsonrpc: '2.0', id: null, error: { code: status === 401 ? AUTH_ERROR_CODE : RPC_ERROR.invalidRequest, message } }, status);
+}
+
+async function principalFor(c: AppContext, token: string): Promise<McpPrincipal> {
+ const access = servicesFor(c).mcpAccess;
+ if (isAccessToken(token)) return access.authenticateToken(token);
+ const { data: { user }, error } = await getSupabaseAuth(c.env).auth.getUser(token);
+ if (error || !user) throw new AppError('UNAUTHORIZED', 'Your Claude connection has expired. Sign in again from Claude.');
+ // only tokens issued to an OAuth client are accepted, so an app session token copied from a browser cannot be replayed here
+ const clientId = oauthClientId(jwtClaims(token));
+ if (!clientId) throw new AppError('UNAUTHORIZED', 'This endpoint takes an access token from Settings, Claude, or a Claude sign-in. App session tokens are not accepted.');
+ return access.authorizeClient(user.id, clientId);
+}
+
+// identity for /mcp: a personal access token or an approved OAuth client, never a request field; sets the same userId
+// the rest of the pipeline trusts
+export async function requireMcpAuth(c: AppContext, next: Next): Promise<Response | void> {
+ const origin = c.req.header('Origin');
+ if (origin && ![...CLAUDE_ORIGINS, ...readConfig(c.env).allowedOrigins].includes(origin)) {
+ return failure(c, 403, 'Requests from this web page are not allowed.');
+ }
+ const token = c.req.header('Authorization')?.match(BEARER)?.[1];
+ if (!token) return failure(c, 401, 'Sign in to use Twiligent from Claude: add an access token from Settings, Claude, or connect with OAuth.');
+ let principal: McpPrincipal;
+ try {
+ principal = await principalFor(c, token);
+ } catch (err) {
+ if (err instanceof AppError && err.code === 'UNAUTHORIZED') return failure(c, 401, err.message);
+ if (err instanceof AppError && err.code === 'FORBIDDEN') return failure(c, 403, err.message);
+ throw err;
+ }
+ c.set('userId', principal.userId);
+ c.set('mcpPrincipal', principal);
+ await next();
+}
diff --git a/backend/routes/index.ts b/backend/routes/index.ts
index ae29cd4..4d7c852 100644
--- a/backend/routes/index.ts
+++ b/backend/routes/index.ts
@@ -5,6 +5,7 @@ import automationRoutes from './automationRoutes.ts';
import analyticsRoutes from './analyticsRoutes.ts';
import instagramAuthRoutes from './instagramAuthRoutes.ts';
import instagramWebhookRoutes from './instagramWebhookRoutes.ts';
+import mcpRoutes from './mcpRoutes.ts';
import overviewRoutes from './overviewRoutes.ts';
import publishingRoutes from './publishingRoutes.ts';
import scheduledPostRoutes from './scheduledPostRoutes.ts';
@@ -29,7 +30,7 @@ publicRoutes.route('/', instagramWebhookRoutes);
export const protectedRoutes = new Hono<AppEnv>();
for (const routes of [
accountRoutes, analyticsRoutes, publishingRoutes, scheduledPostRoutes, trackedContentRoutes,
- overviewRoutes, settingsRoutes, instagramAuthRoutes, automationRoutes,
+ overviewRoutes, settingsRoutes, instagramAuthRoutes, automationRoutes, mcpRoutes,
]) {
protectedRoutes.route('/', routes);
}
diff --git a/backend/routes/mcpRoutes.ts b/backend/routes/mcpRoutes.ts
new file mode 100644
index 0000000..b24ec95
--- /dev/null
+++ b/backend/routes/mcpRoutes.ts
@@ -0,0 +1,18 @@
+import { Hono } from 'hono';
+import {
+ approveClient, createAccessToken, getMcpInfo, listAccessTokens, listClientGrants, revokeAccessToken, revokeClient,
+} from '../controllers/mcpAccessController.ts';
+import type { AppEnv } from '../types/app.ts';
+
+// the Settings page and the consent page manage how Claude clients reach this account; the MCP endpoint is in app.ts
+const router = new Hono<AppEnv>();
+
+router.get('/mcp/info', ...getMcpInfo);
+router.get('/mcp/tokens', ...listAccessTokens);
+router.post('/mcp/tokens', ...createAccessToken);
+router.delete('/mcp/tokens/:id', ...revokeAccessToken);
+router.get('/mcp/clients', ...listClientGrants);
+router.post('/mcp/clients', ...approveClient);
+router.delete('/mcp/clients/:id', ...revokeClient);
+
+export default router;
diff --git a/backend/tests/lib/jwtClaims.test.ts b/backend/tests/lib/jwtClaims.test.ts
new file mode 100644
index 0000000..6c73758
--- /dev/null
+++ b/backend/tests/lib/jwtClaims.test.ts
@@ -0,0 +1,18 @@
+import { test } from 'node:test';
+import assert from 'node:assert/strict';
+import { jwtClaims, oauthClientId } from '../../lib/jwtClaims.ts';
+
+const encode = (value: unknown) => btoa(JSON.stringify(value)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
+
+test('the claims of a token are read from its middle part', () => {
+ const token = `${encode({ alg: 'ES256' })}.${encode({ sub: 'user-1', client_id: 'client-a' })}.signature`;
+ assert.deepEqual(jwtClaims(token), { sub: 'user-1', client_id: 'client-a' });
+ assert.equal(oauthClientId(jwtClaims(token)), 'client-a');
+});
+
+test('an app session token has no client id, and garbage has no claims', () => {
+ assert.equal(oauthClientId(jwtClaims(`x.${encode({ sub: 'user-1', aud: 'authenticated' })}.y`)), null);
+ assert.equal(jwtClaims('not-a-token'), null);
+ assert.equal(jwtClaims('a.***.c'), null);
+ assert.equal(jwtClaims(`a.${encode([1, 2])}.c`), null);
+});
diff --git a/backend/tests/routes/mcpRoutes.test.ts b/backend/tests/routes/mcpRoutes.test.ts
new file mode 100644
index 0000000..d1678cf
--- /dev/null
+++ b/backend/tests/routes/mcpRoutes.test.ts
@@ -0,0 +1,122 @@
+import { test, describe } from 'node:test';
+import assert from 'node:assert/strict';
+import mcpRouter from '../../routes/mcpRoutes.ts';
+import { requireMcpAuth } from '../../middleware/mcpAuth.ts';
+import { getProtectedResourceMetadata, handleMcpMessage, refuseMcpStream } from '../../controllers/mcpController.ts';
+import { hashAccessToken } from '../../lib/mcp/accessToken.ts';
+import { fakeSupabase, tableRow } from '../fixtures/fakeSupabase.ts';
+import { callRoute, mountWithContext } from '../fixtures/routeHarness.ts';
+import type { Row } from '../fixtures/fakeSupabase.ts';
+import type { Env } from '../../types/env.ts';
+
+const READ_TOKEN = 'twl_' + 'r'.repeat(43);
+const OTHER_TOKEN = 'twl_' + 'o'.repeat(43);
+const ENV: Partial<Env> = { BACKEND_URL: 'https://api.example.com', SUPABASE_URL: 'https://ref.supabase.co', TOKEN_ENCRYPTION_KEY: 'k'.repeat(40) };
+const LATER = new Date(Date.now() + 86_400_000).toISOString();
+
+async function tokenRow(token: string, userId: string, permission: 'read' | 'write', extra: Row = {}): Promise<Row> {
+ return tableRow('mcp_access_tokens', { id: `id-${userId}`, user_id: userId, label: 'Laptop', token_hash: await hashAccessToken(token), token_hint: token.slice(-4), permission, created_at: '2026-11-01T00:00:00Z', ...extra });
+}
+
+function postRow(id: string, userId: string): Row {
+ return tableRow('scheduled_posts', { id, user_id: userId, account_id: 'ig-1', status: 'pending', scheduled_at: LATER, claimed_at: null, attempts: 0, data: { caption: `post of ${userId}` } });
+}
+
+function endpoint(rows: Row[]) {
+ const supabase = fakeSupabase(rows);
+ const app = mountWithContext(app => {
+ app.get('/.well-known/oauth-protected-resource/mcp', ...getProtectedResourceMetadata);
+ app.post('/mcp', requireMcpAuth, ...handleMcpMessage);
+ app.on(['GET', 'DELETE'], '/mcp', ...refuseMcpStream);
+ }, { supabase, redis: null, rateLimitRedis: null });
+ return { app, supabase };
+}
+
+const rpc = (method: string, params: Record<string, unknown> = {}) => ({ jsonrpc: '2.0', id: 1, method, params });
+
+describe('the MCP endpoint', () => {
+ test('a request without a token gets 401 with a challenge, naming the metadata only once OAuth is on', async () => {
+ const { app } = endpoint([]);
+ const off = await app.request('/mcp', { method: 'POST', body: JSON.stringify(rpc('tools/list')), headers: { 'Content-Type': 'application/json' } }, ENV);
+ assert.equal(off.status, 401);
+ assert.equal(off.headers.get('WWW-Authenticate'), 'Bearer realm="twiligent"');
+ const on = await app.request('/mcp', { method: 'POST', body: JSON.stringify(rpc('tools/list')), headers: { 'Content-Type': 'application/json' } }, { ...ENV, MCP_OAUTH_ENABLED: 'true' });
+ assert.equal(on.headers.get('WWW-Authenticate'), 'Bearer realm="twiligent", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource/mcp"');
+ });
+
+ test('an unknown or revoked token is refused, and a page on another site is refused before any token check', async () => {
+ const { app } = endpoint([await tokenRow(READ_TOKEN, 'user-1', 'read', { revoked_at: '2026-11-02T00:00:00Z' })]);
+ const revoked = await callRoute(app, 'POST', '/mcp', { json: rpc('tools/list'), headers: { Authorization: `Bearer ${READ_TOKEN}` }, env: ENV });
+ assert.equal(revoked.status, 401);
+ const foreign = await callRoute(app, 'POST', '/mcp', { json: rpc('tools/list'), headers: { Authorization: `Bearer ${READ_TOKEN}`, Origin: 'https://evil.example' }, env: ENV });
+ assert.equal(foreign.status, 403);
+ });
+
+ test('a read token initializes without a session and lists only read tools', async () => {
+ const { app } = endpoint([await tokenRow(READ_TOKEN, 'user-1', 'read')]);
+ const headers = { Authorization: `Bearer ${READ_TOKEN}` };
+ const init = await app.request('/mcp', { method: 'POST', body: JSON.stringify(rpc('initialize', { protocolVersion: '2025-11-25' })), headers: { ...headers, 'Content-Type': 'application/json' } }, ENV);
+ assert.equal(init.status, 200);
+ assert.equal(init.headers.get('Mcp-Session-Id'), null);
+ const list = await callRoute(app, 'POST', '/mcp', { json: rpc('tools/list'), headers: { ...headers, 'MCP-Protocol-Version': '2025-11-25' }, env: ENV });
+ const names = JSON.parse(list.body).result.tools.map((tool: { name: string }) => tool.name);
+ assert.ok(names.includes('list_scheduled_posts'));
+ assert.ok(!names.includes('cancel_scheduled_post'));
+ });
+
+ test('each caller sees only their own scheduled posts', async () => {
+ const { app } = endpoint([await tokenRow(READ_TOKEN, 'user-1', 'read'), await tokenRow(OTHER_TOKEN, 'user-2', 'read'), postRow('p1', 'user-1'), postRow('p2', 'user-2')]);
+ const listFor = async (token: string) => {
+ const reply = await callRoute(app, 'POST', '/mcp', { json: rpc('tools/call', { name: 'list_scheduled_posts', arguments: {} }), headers: { Authorization: `Bearer ${token}` }, env: ENV });
+ return JSON.parse(reply.body).result.structuredContent.posts.map((post: { id: string }) => post.id);
+ };
+ assert.deepEqual(await listFor(READ_TOKEN), ['p1']);
+ assert.deepEqual(await listFor(OTHER_TOKEN), ['p2']);
+ });
+
+ test('a body that is not JSON is a parse error, and GET or DELETE is 405 with no stream', async () => {
+ const { app } = endpoint([await tokenRow(READ_TOKEN, 'user-1', 'read')]);
+ const bad = await callRoute(app, 'POST', '/mcp', { json: '{not json', headers: { Authorization: `Bearer ${READ_TOKEN}` }, env: ENV });
+ assert.equal(bad.status, 400);
+ assert.equal(JSON.parse(bad.body).error.code, -32700);
+ assert.equal((await callRoute(app, 'GET', '/mcp', { env: ENV })).status, 405);
+ assert.equal((await callRoute(app, 'DELETE', '/mcp', { env: ENV })).status, 405);
+ });
+
+ test('the protected resource metadata names Supabase Auth only once OAuth is on', async () => {
+ const { app } = endpoint([]);
+ assert.equal((await callRoute(app, 'GET', '/.well-known/oauth-protected-resource/mcp', { env: ENV })).status, 404);
+ const on = await callRoute(app, 'GET', '/.well-known/oauth-protected-resource/mcp', { env: { ...ENV, MCP_OAUTH_ENABLED: 'true' } });
+ assert.deepEqual(JSON.parse(on.body), {
+ resource: 'https://api.example.com/mcp', authorization_servers: ['https://ref.supabase.co/auth/v1'], bearer_methods_supported: ['header'], resource_name: 'Twiligent',
+ });
+ });
+});
+
+describe('access token management routes', () => {
+ test('a created token is returned once, listed without the token, and revoked only by its owner', async () => {
+ const supabase = fakeSupabase();
+ const asUser = (userId: string) => mountWithContext(app => app.route('/', mcpRouter), { supabase, redis: null, rateLimitRedis: null, userId });
+ const created = await callRoute(asUser('user-1'), 'POST', '/mcp/tokens', { json: { label: 'Laptop', permission: 'write', expiresInDays: 30 }, env: ENV });
+ assert.equal(created.status, 201);
+ const { token, summary } = JSON.parse(created.body);
+ assert.match(token, /^twl_/);
+ const list = await callRoute(asUser('user-1'), 'GET', '/mcp/tokens', { env: ENV });
+ assert.ok(!list.body.includes(token));
+ assert.equal(JSON.parse(list.body).tokens[0].id, summary.id);
+ assert.equal((await callRoute(asUser('user-2'), 'DELETE', `/mcp/tokens/${summary.id}`, { env: ENV })).status, 404);
+ assert.equal((await callRoute(asUser('user-1'), 'DELETE', `/mcp/tokens/${summary.id}`, { env: ENV })).status, 200);
+ });
+
+ test('a token without a name or with an unknown permission is refused', async () => {
+ const app = mountWithContext(app => app.route('/', mcpRouter), { supabase: fakeSupabase(), redis: null, rateLimitRedis: null, userId: 'user-1' });
+ assert.equal((await callRoute(app, 'POST', '/mcp/tokens', { json: { label: '', permission: 'read', expiresInDays: null }, env: ENV })).status, 400);
+ assert.equal((await callRoute(app, 'POST', '/mcp/tokens', { json: { label: 'X', permission: 'admin', expiresInDays: null }, env: ENV })).status, 400);
+ });
+
+ test('the server info gives the URL to paste into Claude', async () => {
+ const app = mountWithContext(app => app.route('/', mcpRouter), { supabase: fakeSupabase(), redis: null, rateLimitRedis: null, userId: 'user-1' });
+ const info = await callRoute(app, 'GET', '/mcp/info', { env: ENV });
+ assert.deepEqual(JSON.parse(info.body), { success: true, serverUrl: 'https://api.example.com/mcp', oauthEnabled: false });
+ });
+});
diff --git a/backend/types/app.ts b/backend/types/app.ts
index bac91f7..20b26dd 100644
--- a/backend/types/app.ts
+++ b/backend/types/app.ts
@@ -2,6 +2,7 @@ import type { Context } from 'hono';
import type { SupabaseClient } from '@supabase/supabase-js';
import type { Redis } from '@upstash/redis';
import type { Env } from './env.ts';
+import type { McpPrincipal } from '../services/mcpAccessService.ts';
export type { SupabaseClient, Redis };
@@ -19,6 +20,8 @@ export interface AppVariables {
// set by requireAuth on protected routes, from the verified JWT only
userId: string;
userEmail: string | undefined;
+ // set by requireMcpAuth on /mcp: who is calling through a Claude client and what they may do
+ mcpPrincipal: McpPrincipal;
}
export interface AppEnv {
diff --git a/backend/validators/mcpValidators.ts b/backend/validators/mcpValidators.ts
index 31be44c..f1f9ebf 100644
--- a/backend/validators/mcpValidators.ts
+++ b/backend/validators/mcpValidators.ts
@@ -21,3 +21,19 @@ export function parseAccessTokenCreate(body: Fields): McpAccessTokenCreateReques
}
return { label, permission: parsePermission(body.permission), expiresInDays };
}
+
+export interface ClientApprovalInput {
+ clientId: string;
+ clientName: string;
+ permission: McpPermission;
+}
+
+const MAX_CLIENT_NAME_LENGTH = 200;
+
+// the consent page sends what Supabase Auth told it about the client; the approval only ever applies to the caller
+export function parseClientApproval(body: Fields): ClientApprovalInput {
+ const clientId = requiredString(body, 'clientId', 'clientId is required').trim();
+ if (clientId.length === 0 || clientId.length > 200) throw new ValidationError('clientId must be 1 to 200 characters');
+ const clientName = requiredString(body, 'clientName', 'clientName is required').trim().slice(0, MAX_CLIENT_NAME_LENGTH) || 'Claude';
+ return { clientId, clientName, permission: parsePermission(body.permission) };
+}