feat(settings): add an MCP connector card with health:read tokens

A dedicated Settings card co-locates the off-by-default MCP module toggle
with token management for connecting an external assistant:

- Mint / list / revoke a dedicated `health:read`-scoped token (shown once,
  copy to clipboard) via new `/api/mcp/tokens` routes — never the
  `medication:ingest` scope, never the wildcard.
- Surface the connector URL and the enable switch in one place, wired to
  the existing module-preference endpoint.
- New section wired into the Settings shell next to API & Tokens, with
  EN + DE strings (and the other locales) under `settings.mcp` and
  `settings.sections.mcp`.
This commit is contained in:
Marc-André Bombeck committed 2026-06-27 14:27:30 +02:00
1 parent 63e4b17843
commit 06363771ee
15 files changed
+632 -6

No files matched your search

+44
View File
@@ -0,0 +1,44 @@
/**
* Revoke an MCP connector token. Only the owning user can revoke; the scope
* filter keeps this endpoint to `health:read` tokens so it can never revoke a
* differently-scoped credential by id alone.
*/
import { apiHandler, requireAuth } from "@/lib/api-handler";
import { apiError, apiSuccess } from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { isApiGloballyEnabled } from "@/lib/app-settings";
import { prisma } from "@/lib/db";
import { SCOPE_HEALTH_READ } from "@/lib/mcp/oauth/config";
type RouteParams = { params: Promise<{ id: string }> };
export const DELETE = apiHandler(
async (_request: Request, { params }: RouteParams) => {
const { user } = await requireAuth();
annotate({ action: { name: "mcp.tokens.revoke" } });
if (!(await isApiGloballyEnabled())) {
return apiError("API is globally disabled", 403);
}
const { id } = await params;
const token = await prisma.apiToken.findUnique({ where: { id } });
if (
!token ||
token.userId !== user.id ||
!token.permissions.includes(SCOPE_HEALTH_READ)
) {
return apiError("Token not found", 404);
}
await prisma.apiToken.update({ where: { id }, data: { revoked: true } });
await auditLog("mcp.tokens.revoke", {
userId: user.id,
details: { tokenId: id },
});
return apiSuccess({ revoked: true });
},
);
+98
View File
@@ -0,0 +1,98 @@
/**
* MCP connector tokens — list + mint.
*
* The MCP settings card mints a DEDICATED `health:read`-scoped Bearer here (NOT
* the `medication:ingest` scope the generic `/api/tokens` mints, and NEVER the
* `["*"]` wildcard). The raw `hlk_` value is shown once. This is the manual /
* stdio / power-user path; the OAuth bridge (`/api/mcp/oauth/*`) mints the same
* `health:read` scope automatically for cloud connectors. Both surface here so
* the user can see and revoke every credential that can read over MCP.
*
* `userId` is always narrowed from the session — never a body field. Scope is
* hardcoded `["health:read"]`, so this endpoint can never be coerced into
* minting a broader grant (no mass assignment).
*/
import { NextRequest } from "next/server";
import { z } from "zod/v4";
import { apiHandler, requireAuth } from "@/lib/api-handler";
import {
apiError,
apiSuccess,
returnAllZodIssues,
safeJson,
} from "@/lib/api-response";
import { annotate } from "@/lib/logging/context";
import { auditLog } from "@/lib/auth/audit";
import { issueApiToken } from "@/lib/auth/issue-token";
import { isApiGloballyEnabled } from "@/lib/app-settings";
import { prisma } from "@/lib/db";
import { SCOPE_HEALTH_READ } from "@/lib/mcp/oauth/config";
const createSchema = z.object({
name: z.string().min(1, "Name required").max(100),
expiresInDays: z.number().int().min(1).max(365).optional(),
});
export const GET = apiHandler(async () => {
const { user } = await requireAuth();
annotate({ action: { name: "mcp.tokens.list" } });
if (!(await isApiGloballyEnabled())) {
return apiError("API is globally disabled", 403);
}
const tokens = await prisma.apiToken.findMany({
where: { userId: user.id, permissions: { has: SCOPE_HEALTH_READ } },
select: {
id: true,
name: true,
permissions: true,
lastUsedAt: true,
expiresAt: true,
createdAt: true,
revoked: true,
},
orderBy: { createdAt: "desc" },
});
return apiSuccess(tokens);
});
export const POST = apiHandler(async (request: NextRequest) => {
const { user } = await requireAuth();
annotate({ action: { name: "mcp.tokens.create" } });
if (!(await isApiGloballyEnabled())) {
return apiError("API is globally disabled", 403);
}
const { data: body, error: jsonError } = await safeJson(request, {
maxBytes: 16 * 1024,
});
if (jsonError) return jsonError;
const parsed = createSchema.safeParse(body);
if (!parsed.success) {
return returnAllZodIssues(parsed.error, 422);
}
const issued = await issueApiToken({
userId: user.id,
name: parsed.data.name,
// Dedicated, least-privilege MCP read scope — never wildcard, never write.
permissions: [SCOPE_HEALTH_READ],
expiresInDays: parsed.data.expiresInDays ?? 90,
});
await auditLog("mcp.tokens.create", {
userId: user.id,
details: { tokenId: issued.tokenId, scope: SCOPE_HEALTH_READ },
});
// Return the raw token ONCE — it can never be retrieved again.
return apiSuccess(
{ token: issued.token, name: issued.name, expiresAt: issued.expiresAt },
201,
);
});