diff --git a/package-lock.json b/package-lock.json index 7d78caf..66ec1ba 100644 --- a/package-lock.json +++ b/package-lock.json @@ -10,6 +10,7 @@ "dependencies": { "@auth/prisma-adapter": "^2.11.1", "@aws-sdk/client-s3": "^3.1000.0", + "@modelcontextprotocol/server": "^2.0.0", "@prisma/client": "^6.19.2", "@tanstack/react-query": "^5.90.21", "@types/bcryptjs": "^2.4.6", @@ -18,6 +19,7 @@ "clsx": "^2.1.1", "html5-qrcode": "^2.3.8", "lucide-react": "^0.575.0", + "mcp-handler": "^2.1.0", "next": "14.2.35", "next-auth": "^5.0.0-beta.25", "openai": "^6.25.0", @@ -1607,6 +1609,31 @@ "@jridgewell/sourcemap-codec": "^1.4.14" } }, + "node_modules/@modelcontextprotocol/core": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/core/-/core-2.0.0.tgz", + "integrity": "sha512-pJCEwGG7Lfr/+PQp9ZTwKXNeO5wzbfKL7H3MYpCorM4oFBoQrdjnBgEoqG+RjhsvS1FKrDbKux+M1HhlnGWqcA==", + "license": "MIT", + "dependencies": { + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/@modelcontextprotocol/server": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/@modelcontextprotocol/server/-/server-2.0.0.tgz", + "integrity": "sha512-YhHWdHfpFMQfd0prsEnxKeS3Qz3ytIGmsS0sth4KDjnacIT7hxk6hXHkJ9KysxlkvTM+WZAtQbbcUhdoP4Hvtw==", + "license": "MIT", + "dependencies": { + "@modelcontextprotocol/core": "2.0.0", + "zod": "^4.2.0" + }, + "engines": { + "node": ">=20" + } + }, "node_modules/@napi-rs/wasm-runtime": { "version": "0.2.12", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", @@ -6125,6 +6152,57 @@ "node": ">= 0.4" } }, + "node_modules/mcp-handler": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mcp-handler/-/mcp-handler-2.1.0.tgz", + "integrity": "sha512-mhnUpkgWrXMwwhdbJ5Uq43uUV23Emxfq3fRfsFwt8Kjc35cGUiKuYeX9wjwnvsdTiKsmjXnQ4tO4awWa3ZM4LQ==", + "license": "Apache-2.0", + "dependencies": { + "chalk": "^5.3.0", + "commander": "^11.1.0" + }, + "bin": { + "create-mcp-route": "dist/cli/index.js", + "mcp-adapter": "dist/cli/index.js", + "mcp-handler": "dist/cli/index.js" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@modelcontextprotocol/server": "^2.0.0", + "next": ">=13.0.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/server": { + "optional": false + }, + "next": { + "optional": true + } + } + }, + "node_modules/mcp-handler/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/mcp-handler/node_modules/commander": { + "version": "11.1.0", + "resolved": "https://registry.npmjs.org/commander/-/commander-11.1.0.tgz", + "integrity": "sha512-yPVavfyCcRhmorC7rWlkHn15b4wDVgVmBA7kV4QVBsF7kv/9TKJAbAXVTxvTnwP8HHKjRCJDClKbciiYS7p0DQ==", + "license": "MIT", + "engines": { + "node": ">=16" + } + }, "node_modules/merge2": { "version": "1.4.1", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", diff --git a/package.json b/package.json index 8963e3f..585b59a 100644 --- a/package.json +++ b/package.json @@ -11,6 +11,7 @@ "dependencies": { "@auth/prisma-adapter": "^2.11.1", "@aws-sdk/client-s3": "^3.1000.0", + "@modelcontextprotocol/server": "^2.0.0", "@prisma/client": "^6.19.2", "@tanstack/react-query": "^5.90.21", "@types/bcryptjs": "^2.4.6", @@ -19,6 +20,7 @@ "clsx": "^2.1.1", "html5-qrcode": "^2.3.8", "lucide-react": "^0.575.0", + "mcp-handler": "^2.1.0", "next": "14.2.35", "next-auth": "^5.0.0-beta.25", "openai": "^6.25.0", diff --git a/prisma/schema.prisma b/prisma/schema.prisma index 07201d1..9b20936 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -58,6 +58,11 @@ model User { invitesCreated Invite[] @relation("InviteCreator") redemption InviteRedemption? passwordResets PasswordReset[] + + mcpTokens McpAccessToken[] + mcpAuditLogs McpAuditLog[] + oauthAuthCodes OAuthAuthCode[] + oauthGrants OAuthGrant[] } // ─── Invites ───────────────────────────────────────────────────── @@ -111,6 +116,143 @@ model PasswordReset { @@index([userId]) } +// ─── MCP access ────────────────────────────────────────────────── +// The app's first header-borne credential. Every other route derives identity +// from the NextAuth JWT cookie, which a machine client (claude.ai, ChatGPT, +// Claude Code) cannot present. + +/// Bearer token for the MCP endpoint. Two producers, one table: a token minted +/// by hand in Settings (source "pat") and one issued by the OAuth token endpoint +/// (source "oauth") are the same row shape, so verification has a single path. +/// +/// Stored as a SHA-256 hash, unlike Invite.token and PasswordReset.token which +/// are plaintext. Those are single-use and short-lived; this one is long-lived +/// and grants full read/write over a user's whole collection, and the nightly +/// pg_dump keeps 14 days of history. +model McpAccessToken { + id String @id @default(cuid()) + userId String + /// sha256 hex of the raw secret - never the secret itself + tokenHash String @unique + /// First 8 chars of the secret, so the UI can tell two tokens apart + prefix String + /// User-supplied label, or the OAuth client name + name String? + scopes String[] + /// "pat" | "oauth" + source String @default("pat") + /// Set only for OAuth-issued tokens; revoking the grant revokes these with it + grantId String? + lastUsedAt DateTime? + expiresAt DateTime? + revokedAt DateTime? + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + grant OAuthGrant? @relation(fields: [grantId], references: [id], onDelete: Cascade) + + @@index([userId]) + @@index([grantId]) + @@index([expiresAt]) +} + +/// One row per MCP tool call. Modelled on AiCall: the arguments are deliberately +/// not recorded - they carry free-text tasting notes and could carry anything. +model McpAuditLog { + id String @id @default(cuid()) + userId String + tokenId String? + tool String + ok Boolean + errorCode String? + /// Row the call created, updated or deleted + recordId String? + durationMs Int? + createdAt DateTime @default(now()) + + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@index([userId, createdAt]) + @@index([createdAt]) +} + +/// A client registered through RFC 7591 dynamic registration. Not user-owned - +/// registrations are global, and a user's access is revoked by cascading their +/// OAuthGrant instead. +model OAuthClient { + id String @id @default(cuid()) + clientId String @unique + clientName String + redirectUris String[] + grantTypes String[] @default(["authorization_code", "refresh_token"]) + responseTypes String[] @default(["code"]) + /// Public clients only - this server stores no client secrets + tokenEndpointAuthMethod String @default("none") + scope String? + clientUri String? + logoUri String? + softwareId String? + createdAt DateTime @default(now()) + lastUsedAt DateTime? + + authCodes OAuthAuthCode[] + grants OAuthGrant[] + + @@index([createdAt]) +} + +/// Authorization code, hashed and single-use. Consumed with a guarded updateMany +/// so a replayed code cannot mint a second token. +model OAuthAuthCode { + id String @id @default(cuid()) + codeHash String @unique + clientId String + userId String + /// Exactly what was sent to /oauth/authorize - re-checked at the token endpoint + redirectUri String + /// RFC 8707 audience binding + resource String? + scopes String[] + codeChallenge String + codeChallengeMethod String @default("S256") + expiresAt DateTime + consumedAt DateTime? + createdAt DateTime @default(now()) + + client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + + @@index([userId]) + @@index([expiresAt]) +} + +/// A user's standing consent for one client. Holds the refresh token, since +/// rotation replaces it while the grant itself persists. +model OAuthGrant { + id String @id @default(cuid()) + clientId String + userId String + scopes String[] + + refreshHash String? @unique + /// One generation back. A hit here means a rotated token was replayed, which + /// is a theft signal - revoke the whole grant rather than issuing again. + refreshPrevHash String? + refreshExpiresAt DateTime? + + revokedAt DateTime? + lastUsedAt DateTime? + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + + client OAuthClient @relation(fields: [clientId], references: [id], onDelete: Cascade) + user User @relation(fields: [userId], references: [id], onDelete: Cascade) + accessTokens McpAccessToken[] + + @@unique([clientId, userId]) + @@index([userId]) +} + model Account { id String @id @default(cuid()) userId String diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts new file mode 100644 index 0000000..6acfa91 --- /dev/null +++ b/src/app/api/mcp/route.ts @@ -0,0 +1,109 @@ +import { createHash } from "crypto" +import { createMcpHandler, withMcpAuth } from "mcp-handler" +import { rateLimit } from "@/lib/rate-limit" +import { verifyMcpToken } from "@/lib/mcp/auth" +import { + MCP_SERVER_NAME, + MCP_SERVER_VERSION, + mcpBaseUrl, +} from "@/lib/mcp/config" +import { registerTools } from "@/lib/mcp/server" + +/** + * The MCP endpoint. + * + * Lives under /api deliberately: the middleware matcher in src/middleware.ts + * excludes /api precisely because `authorized` answers with an HTML redirect to + * /login, and an MCP client needs a JSON 401 with a WWW-Authenticate challenge. + * Authentication here is a bearer token, never the session cookie. + */ + +export const runtime = "nodejs" +export const dynamic = "force-dynamic" + +const RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource" + +const baseHandler = createMcpHandler(registerTools, { + serverInfo: { name: MCP_SERVER_NAME, version: MCP_SERVER_VERSION }, + verboseLogs: process.env.NODE_ENV !== "production", +}) + +const authedHandler = withMcpAuth(baseHandler, verifyMcpToken, { + required: true, + resourceMetadataPath: RESOURCE_METADATA_PATH, + // Pinned rather than derived from proxy headers. See src/lib/mcp/config.ts - + // the app binds 0.0.0.0:3000 behind a reverse proxy, so a request-derived + // origin sends clients to an unreachable metadata URL. + resourceUrl: mcpBaseUrl(), +}) + +/** + * A wildcard origin is safe here only because this endpoint authenticates with an + * Authorization header and never a cookie. Do not add Access-Control-Allow- + * Credentials, and do not add session-cookie auth as a fallback: either one turns + * this into a CSRF hole that any website could drive on a logged-in user's behalf. + */ +const CORS_HEADERS: Record = { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET, POST, DELETE, OPTIONS", + "Access-Control-Allow-Headers": + "Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID", + "Access-Control-Expose-Headers": "Mcp-Session-Id, WWW-Authenticate", + "Access-Control-Max-Age": "86400", +} + +function withCors(response: Response): Response { + for (const [key, value] of Object.entries(CORS_HEADERS)) { + response.headers.set(key, value) + } + return response +} + +/** + * Throttled on a hash of the presented credential, so it works before any + * database lookup and a malformed token cannot be used to probe for free. + * + * Deliberately not enforced inside verifyMcpToken: returning undefined there + * produces a 401, which tells the client to go and re-authenticate - the wrong + * answer to "slow down", and one that would send Claude around the OAuth loop + * repeatedly. Note src/lib/rate-limit.ts is a module-scope Map: per process and + * reset by every deploy. Correct for the single systemd process this runs as; + * under multiple workers the effective limit becomes N times looser. + */ +function throttle(request: Request): Response | null { + const bearer = request.headers + .get("authorization") + ?.replace(/^Bearer\s+/i, "") + .trim() + + const key = bearer + ? `mcp:${createHash("sha256").update(bearer).digest("hex").slice(0, 16)}` + : "mcp:anonymous" + + const { success } = rateLimit(key, 120, 60_000) + if (success) return null + + return withCors( + new Response( + JSON.stringify({ error: "Too many requests. Please slow down." }), + { + status: 429, + headers: { "content-type": "application/json", "retry-after": "60" }, + } + ) + ) +} + +async function handle(request: Request): Promise { + const throttled = throttle(request) + if (throttled) return throttled + return withCors(await authedHandler(request)) +} + +export const GET = handle +export const POST = handle +export const DELETE = handle + +export function OPTIONS(): Response { + return withCors(new Response(null, { status: 204 })) +} diff --git a/src/app/api/settings/mcp-tokens/[id]/route.ts b/src/app/api/settings/mcp-tokens/[id]/route.ts new file mode 100644 index 0000000..6a44257 --- /dev/null +++ b/src/app/api/settings/mcp-tokens/[id]/route.ts @@ -0,0 +1,29 @@ +import { NextResponse } from "next/server" +import { requireUser } from "@/lib/authz" +import { prisma } from "@/lib/prisma" + +/** + * Revoke a token. Soft, so the row survives for the audit trail; verifyMcpToken + * checks revokedAt on every request with no cache anywhere, so it takes effect + * on the next call. + */ +export async function DELETE( + _request: Request, + { params }: { params: { id: string } } +) { + const session = await requireUser() + if (session instanceof NextResponse) return session + + // Scoped to the caller, resolving to 404 rather than 403 - the convention + // across the rest of the API. + const { count } = await prisma.mcpAccessToken.updateMany({ + where: { id: params.id, userId: session.user.id, revokedAt: null }, + data: { revokedAt: new Date() }, + }) + + if (count === 0) { + return NextResponse.json({ error: "Not found" }, { status: 404 }) + } + + return NextResponse.json({ success: true }) +} diff --git a/src/app/api/settings/mcp-tokens/route.ts b/src/app/api/settings/mcp-tokens/route.ts new file mode 100644 index 0000000..f7c1eb0 --- /dev/null +++ b/src/app/api/settings/mcp-tokens/route.ts @@ -0,0 +1,107 @@ +import { NextResponse } from "next/server" +import { z } from "zod" +import { requireUser } from "@/lib/authz" +import { prisma } from "@/lib/prisma" +import { generateMcpToken } from "@/lib/mcp/tokens" +import { MCP_ALL_SCOPES, MCP_READ_SCOPES, mcpResourceUrl } from "@/lib/mcp/config" + +/** + * MCP access tokens. + * + * requireUser, not requireOwner: a token only ever reaches its own user's rows, + * so a member connecting their own Claude or ChatGPT is no more privileged than + * them logging into the web app. + */ + +/** Enough to cover a laptop, a phone, a desktop client and some spares. */ +const MAX_LIVE_TOKENS = 10 + +const createSchema = z.object({ + name: z.string().min(1).max(100).optional(), + access: z.enum(["read", "read-write"]).default("read"), + expiresInDays: z.union([z.literal(90), z.literal(365), z.null()]).default(90), +}) + +export async function GET() { + const session = await requireUser() + if (session instanceof NextResponse) return session + + const tokens = await prisma.mcpAccessToken.findMany({ + where: { userId: session.user.id, source: "pat", revokedAt: null }, + orderBy: { createdAt: "desc" }, + // The secret is not selectable because it is not stored - only its hash is. + // This is the deliberate difference from /api/settings/api-keys, which + // decrypts and masks on read. + select: { + id: true, + name: true, + prefix: true, + scopes: true, + lastUsedAt: true, + expiresAt: true, + createdAt: true, + }, + }) + + return NextResponse.json({ + tokens, + serverUrl: mcpResourceUrl(), + }) +} + +export async function POST(request: Request) { + const session = await requireUser() + if (session instanceof NextResponse) return session + + const body = await request.json().catch(() => null) + const parsed = createSchema.safeParse(body ?? {}) + if (!parsed.success) { + return NextResponse.json( + { error: "Invalid input", details: parsed.error.flatten() }, + { status: 400 } + ) + } + + const live = await prisma.mcpAccessToken.count({ + where: { userId: session.user.id, source: "pat", revokedAt: null }, + }) + if (live >= MAX_LIVE_TOKENS) { + return NextResponse.json( + { + error: `You already have ${MAX_LIVE_TOKENS} active tokens. Revoke one before creating another.`, + }, + { status: 400 } + ) + } + + const { name, access, expiresInDays } = parsed.data + const { raw, hash, prefix } = generateMcpToken() + + const token = await prisma.mcpAccessToken.create({ + data: { + userId: session.user.id, + tokenHash: hash, + prefix, + name: name ?? null, + scopes: access === "read-write" ? MCP_ALL_SCOPES : MCP_READ_SCOPES, + source: "pat", + expiresAt: expiresInDays + ? new Date(Date.now() + expiresInDays * 24 * 60 * 60 * 1000) + : null, + }, + select: { + id: true, + name: true, + prefix: true, + scopes: true, + expiresAt: true, + createdAt: true, + }, + }) + + // The only time the secret ever leaves this process. + return NextResponse.json( + { token: { ...token, secret: raw }, serverUrl: mcpResourceUrl() }, + { status: 201 } + ) +} diff --git a/src/components/settings/mcp-tokens-card.tsx b/src/components/settings/mcp-tokens-card.tsx new file mode 100644 index 0000000..1469602 --- /dev/null +++ b/src/components/settings/mcp-tokens-card.tsx @@ -0,0 +1,314 @@ +"use client" + +import { useState } from "react" +import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query" +import { + Card, + CardContent, + CardDescription, + CardHeader, + CardTitle, +} from "@/components/ui/card" +import { Button } from "@/components/ui/button" +import { Input } from "@/components/ui/input" +import { Label } from "@/components/ui/label" +import { Badge } from "@/components/ui/badge" +import { Select, SelectOption } from "@/components/ui/select" +import { Check, Copy, Loader2, Plug, Trash2 } from "lucide-react" + +interface McpToken { + id: string + name: string | null + prefix: string + scopes: string[] + lastUsedAt: string | null + expiresAt: string | null + createdAt: string +} + +interface TokensResponse { + tokens: McpToken[] + serverUrl: string +} + +interface CreatedToken extends McpToken { + secret: string +} + +const ACCESS_OPTIONS = [ + { value: "read", label: "Read only" }, + { value: "read-write", label: "Read and write" }, +] + +const EXPIRY_OPTIONS = [ + { value: "90", label: "90 days" }, + { value: "365", label: "1 year" }, + { value: "never", label: "Never" }, +] + +/** + * Connecting an AI assistant to this account. + * + * Not gated on ownership, unlike the AI Gateway card: a token only ever reaches + * its own user's rows, and it spends nothing. + */ +export function McpTokensCard() { + const queryClient = useQueryClient() + const [name, setName] = useState("") + const [access, setAccess] = useState("read") + const [expiry, setExpiry] = useState("90") + const [created, setCreated] = useState(null) + const [copied, setCopied] = useState(null) + + const { data, isLoading } = useQuery({ + queryKey: ["mcp-tokens"], + queryFn: async () => { + const res = await fetch("/api/settings/mcp-tokens") + if (!res.ok) throw new Error("Failed to load tokens") + return res.json() + }, + }) + + const create = useMutation({ + mutationFn: async () => { + const res = await fetch("/api/settings/mcp-tokens", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + name: name.trim() || undefined, + access, + expiresInDays: expiry === "never" ? null : Number(expiry), + }), + }) + const body = await res.json() + if (!res.ok) throw new Error(body.error ?? "Failed to create token") + return body as { token: CreatedToken; serverUrl: string } + }, + onSuccess: (body) => { + setCreated(body.token) + setName("") + queryClient.invalidateQueries({ queryKey: ["mcp-tokens"] }) + }, + }) + + const revoke = useMutation({ + mutationFn: async (id: string) => { + const res = await fetch(`/api/settings/mcp-tokens/${id}`, { + method: "DELETE", + }) + if (!res.ok) throw new Error("Failed to revoke token") + }, + onSuccess: () => { + queryClient.invalidateQueries({ queryKey: ["mcp-tokens"] }) + }, + }) + + const serverUrl = data?.serverUrl ?? "" + + async function copy(key: string, value: string) { + await navigator.clipboard.writeText(value) + setCopied(key) + setTimeout(() => setCopied(null), 2000) + } + + const connectCommand = created + ? `claude mcp add --transport http drinktracker ${serverUrl} --header "Authorization: Bearer ${created.secret}" -s user` + : "" + + return ( + + + + + AI assistant access + + + Connect Claude or ChatGPT to this account so it can read and update your + drinks, bar and recipes. Each token reaches only your own data. + + + + + {created && ( +
+
+
+

Your new token

+

+ Copy it now. It is stored only as a hash, so it cannot be shown + again. +

+
+ +
+ +
+ + {created.secret} + + +
+ +
+

Connect Claude Code

+
+ + {connectCommand} + + +
+
+
+ )} + +
+
+ + setName(e.target.value)} + /> +
+
+ + +
+
+ + +
+
+ +
+ + {create.isError && ( +

+ {(create.error as Error).message} +

+ )} +
+ +
+ {isLoading && ( +

Loading…

+ )} + {!isLoading && !data?.tokens.length && ( +

+ No tokens yet. Create one to connect an assistant. +

+ )} + {data?.tokens.map((token) => ( +
+
+
+ + {token.name ?? "Unnamed token"} + + + dtk_{token.prefix}… + + + {token.scopes.some((s) => s.endsWith(":write")) + ? "read/write" + : "read only"} + + +
+

+ {token.lastUsedAt + ? `Last used ${new Date(token.lastUsedAt).toLocaleDateString()}` + : "Never used"} +

+
+ +
+ ))} +
+ + {serverUrl && ( +

+ Server URL: {serverUrl} +

+ )} +
+
+ ) +} + +function ExpiryBadge({ expiresAt }: { expiresAt: string | null }) { + if (!expiresAt) return no expiry + + const days = Math.ceil( + (new Date(expiresAt).getTime() - Date.now()) / (24 * 60 * 60 * 1000) + ) + if (days <= 0) return expired + // Flagged early enough to rotate before a client starts failing. + if (days <= 14) return {days}d left + return {days}d left +} diff --git a/src/components/settings/settings-client.tsx b/src/components/settings/settings-client.tsx index b1ed110..efcc92f 100644 --- a/src/components/settings/settings-client.tsx +++ b/src/components/settings/settings-client.tsx @@ -11,6 +11,7 @@ import { Badge } from "@/components/ui/badge" import { Separator } from "@/components/ui/separator" import { Key, Trash2, Check, Loader2, Shield, Sliders } from "lucide-react" import { BackupRestore } from "@/components/settings/backup-restore" +import { McpTokensCard } from "@/components/settings/mcp-tokens-card" import { DeleteAccountCard } from "@/components/settings/delete-account-card" interface ApiKeyInfo { @@ -140,6 +141,10 @@ export function SettingsClient({ isOwner }: { isOwner: boolean }) { + {/* Available to every member: an MCP token only ever reaches its own + user's rows, and unlike the gateway key it spends nothing. */} + + {/* Backup & Restore Section */} diff --git a/src/lib/mcp/audit.ts b/src/lib/mcp/audit.ts new file mode 100644 index 0000000..ad3d075 --- /dev/null +++ b/src/lib/mcp/audit.ts @@ -0,0 +1,46 @@ +import { prisma } from "@/lib/prisma" + +/** + * One row per MCP tool call, modelled on AiCall - same shape, same reason. Once a + * long-lived credential can write to someone's collection, "what did that token + * actually do" needs to be a query rather than a journald grep. + * + * The arguments are deliberately not recorded. They carry free-text tasting notes + * and could carry anything a user typed; the tool name plus the affected row id is + * enough to reconstruct what happened without turning the audit log into a second + * copy of the data it is auditing. + */ + +export interface McpCallLog { + userId: string + tokenId?: string | null + tool: string + ok: boolean + errorCode?: string | null + recordId?: string | null + durationMs?: number | null +} + +export function logMcpCall(entry: McpCallLog): void { + // Matches the existing [switchboard] convention, which deploy.sh already greps + // for when checking a release. + const status = entry.ok ? "ok" : `err=${entry.errorCode ?? "unknown"}` + console.log( + `[mcp] user=${entry.userId} tool=${entry.tool} ${status} ms=${entry.durationMs ?? "?"}` + ) + + // Fire and forget: an audit write must never fail the call it is auditing. + prisma.mcpAuditLog + .create({ + data: { + userId: entry.userId, + tokenId: entry.tokenId ?? null, + tool: entry.tool, + ok: entry.ok, + errorCode: entry.errorCode ?? null, + recordId: entry.recordId ?? null, + durationMs: entry.durationMs ?? null, + }, + }) + .catch((error) => console.warn("[mcp] audit write failed:", error)) +} diff --git a/src/lib/mcp/auth.ts b/src/lib/mcp/auth.ts new file mode 100644 index 0000000..0f1c69a --- /dev/null +++ b/src/lib/mcp/auth.ts @@ -0,0 +1,99 @@ +import type { AuthInfo } from "@modelcontextprotocol/server" +import { prisma } from "@/lib/prisma" +import { hashMcpToken, looksLikeMcpToken } from "@/lib/mcp/tokens" + +/** + * The single place an MCP bearer token becomes a user. + * + * Both token sources land here: one minted by hand in Settings (source "pat") and + * one issued by the OAuth token endpoint (source "oauth") are the same row, so + * adding OAuth does not add a second verification path to keep in sync. + */ + +/** Don't write lastUsedAt more often than this. */ +const TOUCH_INTERVAL_MS = 5 * 60 * 1000 + +export interface McpCaller { + userId: string + tokenId: string + scopes: string[] + role: "OWNER" | "MEMBER" +} + +export async function verifyMcpToken( + _request: Request, + bearerToken?: string +): Promise { + // Cheap shape check first - no query for a malformed header. + if (!looksLikeMcpToken(bearerToken)) return undefined + + let row + try { + row = await prisma.mcpAccessToken.findUnique({ + where: { tokenHash: hashMcpToken(bearerToken) }, + select: { + id: true, + userId: true, + scopes: true, + source: true, + grantId: true, + expiresAt: true, + revokedAt: true, + lastUsedAt: true, + // Joined rather than queried separately: this is what makes suspension + // take effect immediately, and it is a foreign key so it costs nothing. + user: { select: { status: true, role: true } }, + grant: { select: { revokedAt: true } }, + }, + }) + } catch (error) { + // Fail closed. This is a deliberate divergence from the jwt callback in + // src/lib/auth.ts, which swallows database errors and keeps the session + // because a throw there signs out every user at once. Here the blast radius + // of a 401 is one client retrying, so there is nothing to protect against. + console.error("[mcp] token lookup failed:", error) + return undefined + } + + if (!row) return undefined + if (row.revokedAt) return undefined + if (row.expiresAt && row.expiresAt.getTime() <= Date.now()) return undefined + // An OAuth token dies with the grant that issued it. + if (row.grant?.revokedAt) return undefined + // Mirrors src/lib/auth.ts, where the jwt callback returns null for a suspended + // user. Without this an MCP token would be a documented way to outlive a + // suspension - the only control an owner has over a member. + if (row.user.status !== "ACTIVE") return undefined + + touchLastUsed(row.id, row.lastUsedAt) + + return { + token: bearerToken, + clientId: row.source === "oauth" ? `oauth:${row.grantId}` : `pat:${row.id}`, + scopes: row.scopes, + // AuthInfo wants seconds since epoch, not a Date. + expiresAt: row.expiresAt + ? Math.floor(row.expiresAt.getTime() / 1000) + : undefined, + extra: { + userId: row.userId, + tokenId: row.id, + grantId: row.grantId, + source: row.source, + role: row.user.role, + }, + } +} + +/** + * Fire and forget, and throttled. Awaiting a write on every tool call would add a + * round trip to every request to record something only ever read by a human + * glancing at the token list. + */ +function touchLastUsed(id: string, lastUsedAt: Date | null): void { + if (lastUsedAt && Date.now() - lastUsedAt.getTime() < TOUCH_INTERVAL_MS) return + + prisma.mcpAccessToken + .update({ where: { id }, data: { lastUsedAt: new Date() } }) + .catch((error) => console.warn("[mcp] lastUsedAt update failed:", error)) +} diff --git a/src/lib/mcp/config.ts b/src/lib/mcp/config.ts new file mode 100644 index 0000000..39a3dd0 --- /dev/null +++ b/src/lib/mcp/config.ts @@ -0,0 +1,61 @@ +/** + * Static configuration for the MCP server. + * + * The origin is read from NEXTAUTH_URL rather than derived from the incoming + * request. `publicOrigin()` in src/lib/origin.ts explains why for links; here it + * matters more. RFC 9728 requires the `resource` field of the protected resource + * metadata to match the URL the user typed into their client byte for byte, and + * RFC 8414 requires the OAuth `issuer` to equal the origin it was discovered at. + * Deriving either from X-Forwarded-* means a proxy misconfiguration shows up as a + * silent connector failure with no useful error, so it is pinned to config instead. + */ + +export const MCP_SERVER_NAME = "drinktracker" +export const MCP_SERVER_VERSION = "1.0.0" + +/** Path the MCP endpoint is mounted at. Clients are given the full URL. */ +export const MCP_PATH = "/api/mcp" + +/** + * Scopes. Two axes, read and write, over two halves of the data: + * + * drinks:* the collection and journal - drinks, ratings, wishlist, preferences + * bar:* the inventory and what can be made from it - bar items, recipes + * + * Kept deliberately coarse. A consent screen listing eight scopes is a consent + * screen nobody reads. + */ +export const MCP_SCOPES = [ + "drinks:read", + "drinks:write", + "bar:read", + "bar:write", +] as const + +export type McpScope = (typeof MCP_SCOPES)[number] + +/** Everything a read-only connection gets. The default when minting a token. */ +export const MCP_READ_SCOPES: McpScope[] = ["drinks:read", "bar:read"] + +/** Full access. */ +export const MCP_ALL_SCOPES: McpScope[] = [...MCP_SCOPES] + +export function isMcpScope(value: string): value is McpScope { + return (MCP_SCOPES as readonly string[]).includes(value) +} + +/** Public origin, no trailing slash. */ +export function mcpBaseUrl(): string { + const configured = process.env.NEXTAUTH_URL + if (configured) return configured.replace(/\/$/, "") + // Only reachable in local development, where NEXTAUTH_URL is usually unset. + return "http://localhost:3000" +} + +/** + * The resource identifier for this MCP server, which is also the URL a user + * pastes into claude.ai. Must match their input exactly. + */ +export function mcpResourceUrl(): string { + return `${mcpBaseUrl()}${MCP_PATH}` +} diff --git a/src/lib/mcp/context.ts b/src/lib/mcp/context.ts new file mode 100644 index 0000000..08f8592 --- /dev/null +++ b/src/lib/mcp/context.ts @@ -0,0 +1,55 @@ +import type { AuthInfo } from "@modelcontextprotocol/server" +import type { McpCaller } from "@/lib/mcp/auth" +import type { McpScope } from "@/lib/mcp/config" + +/** + * Pulling the authenticated user out of a tool callback. + * + * In SDK v2 the verified token is at `ctx.http.authInfo` (it was `extra.authInfo` + * in v1). The context type is wide, so this narrows it in one place rather than + * casting in seventeen tool handlers. + */ + +/** Thrown by the helpers below; surfaces to the client as an error tool result. */ +export class McpToolError extends Error { + readonly code: string + + constructor(message: string, code = "forbidden") { + super(message) + this.name = "McpToolError" + this.code = code + } +} + +interface MaybeHttpContext { + http?: { authInfo?: AuthInfo } +} + +export function requireMcpUser(ctx: unknown): McpCaller { + const authInfo = (ctx as MaybeHttpContext | undefined)?.http?.authInfo + const extra = authInfo?.extra + + const userId = extra?.userId + const tokenId = extra?.tokenId + if (typeof userId !== "string" || typeof tokenId !== "string") { + // Unreachable in practice - withMcpAuth runs with `required: true`, so an + // unauthenticated request never reaches a tool. Kept so a future misuse of + // the handler fails loudly rather than reading someone else's rows. + throw new McpToolError("Not authenticated.", "unauthorized") + } + + return { + userId, + tokenId, + scopes: authInfo?.scopes ?? [], + role: extra?.role === "OWNER" ? "OWNER" : "MEMBER", + } +} + +export function requireScope(caller: McpCaller, scope: McpScope): void { + if (caller.scopes.includes(scope)) return + throw new McpToolError( + `This connection does not have the "${scope}" permission. Reconnect with a read-write token to do that.`, + "insufficient_scope" + ) +} diff --git a/src/lib/mcp/define.ts b/src/lib/mcp/define.ts new file mode 100644 index 0000000..c4ee80d --- /dev/null +++ b/src/lib/mcp/define.ts @@ -0,0 +1,118 @@ +import type { CallToolResult, McpServer } from "@modelcontextprotocol/server" +import type { z } from "zod" +import type { McpCaller } from "@/lib/mcp/auth" +import type { McpScope } from "@/lib/mcp/config" +import { McpToolError, requireMcpUser, requireScope } from "@/lib/mcp/context" +import { logMcpCall } from "@/lib/mcp/audit" +import { fail } from "@/lib/mcp/render" + +/** + * Registers a tool with the auth, scope, error and audit handling every tool + * needs, so seventeen handlers can be seventeen queries instead of seventeen + * copies of the same six lines. + * + * Handlers return either a CallToolResult or a `{ result, recordId }` pair - the + * recordId is what the audit row records as the row touched. + */ + +export interface ToolSpec { + name: string + title: string + description: string + inputSchema: S + /** Required scope. Omit only for tools that need no permission at all. */ + scope?: McpScope + /** True for tools that never write. Surfaces as an MCP annotation. */ + readOnly?: boolean + /** True for tools that delete data. */ + destructive?: boolean +} + +export interface ToolOutcome { + result: CallToolResult + recordId?: string | null +} + +export type ToolHandler = ( + args: z.infer, + caller: McpCaller +) => Promise + +/** + * CallToolResult carries an index signature, so `"result" in outcome` does not + * narrow. Probe for the nested content array instead. + */ +function isToolOutcome(value: CallToolResult | ToolOutcome): value is ToolOutcome { + const nested = (value as ToolOutcome).result + return !!nested && typeof nested === "object" && Array.isArray(nested.content) +} + +export function defineTool( + server: McpServer, + spec: ToolSpec, + handler: ToolHandler +): void { + server.registerTool( + spec.name, + { + title: spec.title, + description: spec.description, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + inputSchema: spec.inputSchema as any, + annotations: { + readOnlyHint: spec.readOnly ?? false, + destructiveHint: spec.destructive ?? false, + }, + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (async (args: any, ctx: unknown) => { + const started = Date.now() + let caller: McpCaller | undefined + + try { + caller = requireMcpUser(ctx) + if (spec.scope) requireScope(caller, spec.scope) + + const outcome = await handler(args as z.infer, caller) + const normalised: ToolOutcome = isToolOutcome(outcome) + ? outcome + : { result: outcome } + + logMcpCall({ + userId: caller.userId, + tokenId: caller.tokenId, + tool: spec.name, + ok: !normalised.result.isError, + recordId: normalised.recordId, + durationMs: Date.now() - started, + }) + + return normalised.result + } catch (error) { + // A throw inside a handler becomes an error tool result, not an HTTP + // status. That is the right shape mid-call: the connection is fine, this + // one operation is not, and the model can read the reason and adapt. + const isExpected = error instanceof McpToolError + if (!isExpected) console.error(`[mcp] ${spec.name} failed:`, error) + + if (caller) { + logMcpCall({ + userId: caller.userId, + tokenId: caller.tokenId, + tool: spec.name, + ok: false, + errorCode: isExpected ? error.code : "internal_error", + durationMs: Date.now() - started, + }) + } + + return fail( + isExpected + ? error.message + : "Something went wrong handling that request." + ) + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + }) as any + ) +} diff --git a/src/lib/mcp/render.ts b/src/lib/mcp/render.ts new file mode 100644 index 0000000..361d137 --- /dev/null +++ b/src/lib/mcp/render.ts @@ -0,0 +1,160 @@ +import type { CallToolResult } from "@modelcontextprotocol/server" + +/** + * Shaping tool output. + * + * Every result carries both `content` text and `structuredContent`. The text is + * what Claude actually reads; structuredContent is there for clients that parse + * it. No `outputSchema` is declared anywhere - declaring one makes + * structuredContent mandatory per spec and adds schema bloat to every tools/list, + * whereas returning it undeclared is allowed. + * + * Text is compact lines, never a JSON dump. The id comes first on every line so + * the model can quote it straight into the next call - every write tool takes one. + */ + +/** + * claude.ai accepts about 150,000 characters per tool result. This budget is far + * lower on purpose: the model pays for every character on every subsequent turn, + * so a result worth truncating is a result worth paginating. + */ +export const MAX_TOOL_TEXT = 40_000 + +/** Hard ceiling on any list tool's page size. The REST API allows 100. */ +export const MAX_PAGE_SIZE = 50 +export const DEFAULT_PAGE_SIZE = 20 + +export function truncateToolText(text: string, limit = MAX_TOOL_TEXT): string { + if (text.length <= limit) return text + const cut = text.slice(0, limit) + // Don't strand a half-written line - the model may try to parse it as an id. + const lastBreak = cut.lastIndexOf("\n") + const body = lastBreak > limit * 0.8 ? cut.slice(0, lastBreak) : cut + return `${body}\n… output truncated. Narrow the search or request the next page.` +} + +export function ok( + text: string, + structuredContent?: Record +): CallToolResult { + return { + content: [{ type: "text", text: truncateToolText(text) }], + ...(structuredContent ? { structuredContent } : {}), + } +} + +export function fail(message: string): CallToolResult { + return { content: [{ type: "text", text: message }], isError: true } +} + +/** + * The trailer models follow reliably. Always emitted by list tools, even on a + * single page, so "is there more" never needs a second call to answer. + */ +export function paginationTrailer( + page: number, + pageSize: number, + total: number +): string { + const totalPages = Math.max(1, Math.ceil(total / pageSize)) + if (total === 0) return "no matches" + const more = + page < totalPages ? ` · pass page=${page + 1} for more` : " · end of results" + return `page ${page} of ${totalPages} · ${total} total${more}` +} + +/** Joins non-empty parts with a separator, dropping blanks. */ +function join(parts: (string | null | undefined)[], sep = " · "): string { + return parts.filter((p): p is string => !!p && p.length > 0).join(sep) +} + +export function formatAbv(abv: number | null | undefined): string | null { + return typeof abv === "number" ? `${abv.toFixed(1)}%` : null +} + +export function formatDrinkLine(d: { + id: string + name: string + type: string + subType?: string | null + brewery?: string | null + region?: string | null + abv?: number | null + avgRating?: number | null + ratingCount?: number +}): string { + const kind = d.subType ? `${d.type} / ${d.subType}` : d.type + const rating = + d.avgRating != null && d.ratingCount + ? `★${d.avgRating.toFixed(1)} (${d.ratingCount})` + : "unrated" + return `[${d.id}] ${d.name} — ${join([ + kind, + d.brewery, + d.region, + formatAbv(d.abv), + rating, + ])}` +} + +export function formatBarItemLine(b: { + id: string + name: string + category: string + quantity: string + notes?: string | null +}): string { + return `[${b.id}] ${b.name} — ${join([b.category, b.quantity, b.notes])}` +} + +export function formatRatingLine(r: { + id: string + score: number + wouldReorder: boolean + location?: string | null + notes?: string | null + createdAt: Date + drink?: { name: string } | null +}): string { + const when = r.createdAt.toISOString().slice(0, 10) + return `[${r.id}] ${r.drink?.name ?? "?"} — ${join([ + `★${r.score}`, + when, + r.location, + r.wouldReorder ? "would reorder" : null, + r.notes, + ])}` +} + +export function formatRecipeLine(r: { + id: string + title: string + missingCount: number + ingredients: { name: string; available: boolean }[] + glassware?: string | null +}): string { + const status = + r.missingCount === 0 + ? "can make now" + : `missing ${r.missingCount}: ${r.ingredients + .filter((i) => !i.available) + .map((i) => i.name) + .join(", ")}` + return `[${r.id}] ${r.title} — ${join([ + `${r.ingredients.length} ingredients`, + status, + r.glassware, + ])}` +} + +export function formatWishlistLine(w: { + id: string + name: string + type: string + subType?: string | null + brewery?: string | null + notes?: string | null +}): string { + const kind = w.subType ? `${w.type} / ${w.subType}` : w.type + return `[${w.id}] ${w.name} — ${join([kind, w.brewery, w.notes])}` +} diff --git a/src/lib/mcp/schemas.ts b/src/lib/mcp/schemas.ts new file mode 100644 index 0000000..389a5c7 --- /dev/null +++ b/src/lib/mcp/schemas.ts @@ -0,0 +1,147 @@ +import { z } from "zod" +import { + barItemCreateSchema, + drinkCreateSchema, + drinkUpdateSchema, + ratingCreateSchema, + ratingUpdateSchema, + recipeCreateSchema, + wishlistCreateSchema, +} from "@/lib/validators" +import { DEFAULT_PAGE_SIZE, MAX_PAGE_SIZE } from "@/lib/mcp/render" + +/** + * Tool input schemas. + * + * Derived from src/lib/validators.ts wherever one exists, so an MCP write and a + * write from the web app cannot drift apart in what they accept. SDK v2 takes a + * full Standard Schema (a `z.object(...)`), not a raw shape, and this project is + * already on zod 4 - so these drop straight in as `inputSchema`. + * + * `imageUrl` is omitted from every one of them. The image route is session-cookie + * gated with per-user key prefixes, so a bearer holder cannot fetch the bytes + * anyway, and a model has no way to produce a valid /minio-images/ path. Letting + * it write arbitrary URLs into a field the app renders in would be stored + * content risk for no benefit. + */ + +const DRINK_TYPES = ["BEER", "WINE", "COCKTAIL", "SPIRIT", "OTHER"] as const + +const idField = z.string().min(1).describe("The id from a previous list result") + +const pageFields = { + page: z.number().int().min(1).default(1).describe("1-based page number"), + limit: z + .number() + .int() + .min(1) + .max(MAX_PAGE_SIZE) + .default(DEFAULT_PAGE_SIZE) + .describe(`Results per page (max ${MAX_PAGE_SIZE})`), +} + +// ─── Drinks ────────────────────────────────────────────────────── + +export const listDrinksSchema = z.object({ + search: z + .string() + .max(200) + .optional() + .describe("Matches name, brewery, sub-type or region, case-insensitively"), + type: z.enum(DRINK_TYPES).optional().describe("Filter to one kind of drink"), + sort: z + .enum(["recent", "name", "rating"]) + .default("recent") + .describe("Order of results"), + ...pageFields, +}) + +export const getDrinkSchema = z.object({ id: idField }) + +export const createDrinkSchema = drinkCreateSchema.omit({ imageUrl: true }) + +export const updateDrinkSchema = drinkUpdateSchema + .omit({ imageUrl: true }) + .extend({ id: idField }) + +export const deleteDrinkSchema = z.object({ id: idField }) + +// ─── Ratings ───────────────────────────────────────────────────── + +export const listRatingsSchema = z.object({ + drinkId: z.string().optional().describe("Only ratings for this drink"), + sort: z.enum(["recent", "score-high", "score-low"]).default("recent"), + ...pageFields, +}) + +export const rateDrinkSchema = ratingCreateSchema + +export const updateRatingSchema = ratingUpdateSchema.extend({ id: idField }) + +// ─── Bar ───────────────────────────────────────────────────────── + +export const listBarItemsSchema = z.object({ + category: z + .enum(["SPIRITS", "LIQUEURS", "MIXERS", "BITTERS", "GARNISHES", "TOOLS"]) + .optional(), + includeEmpty: z + .boolean() + .default(true) + .describe("Set false to hide bottles marked EMPTY"), +}) + +/** + * One tool for add and update. "I bought gin" and "I finished the gin" are the + * same gesture to a model, and forcing it to choose between two tools it cannot + * distinguish without a prior lookup just costs a round trip. + */ +export const upsertBarItemSchema = barItemCreateSchema + .omit({ imageUrl: true }) + .extend({ + id: z + .string() + .optional() + .describe("Omit to add a new bottle; pass an existing id to update it"), + }) + +export const deleteBarItemSchema = z.object({ id: idField }) + +// ─── Recipes ───────────────────────────────────────────────────── + +export const listRecipesSchema = z.object({ + makeableOnly: z + .boolean() + .default(false) + .describe("Only recipes where every ingredient is currently in the bar"), + search: z.string().max(200).optional().describe("Matches the recipe title"), +}) + +export const saveRecipeSchema = recipeCreateSchema + +export const deleteRecipeSchema = z.object({ id: idField }) + +// ─── Wishlist ──────────────────────────────────────────────────── + +export const listWishlistSchema = z.object({}) + +// `source` is set by the server to "mcp" so wishlist entries added this way are +// attributable, the same way the scan and ai_search paths tag their own. +export const addWishlistItemSchema = wishlistCreateSchema.omit({ source: true }) + +export const removeWishlistItemSchema = z.object({ id: idField }) + +export const promoteWishlistItemSchema = z.object({ id: idField }) + +// ─── Meta ──────────────────────────────────────────────────────── + +export const emptySchema = z.object({}) + +// ─── ChatGPT deep-research compatibility ───────────────────────── + +export const chatgptSearchSchema = z.object({ + query: z.string().min(1).max(200), +}) + +export const chatgptFetchSchema = z.object({ + id: idField, +}) diff --git a/src/lib/mcp/server.ts b/src/lib/mcp/server.ts new file mode 100644 index 0000000..b4b1a17 --- /dev/null +++ b/src/lib/mcp/server.ts @@ -0,0 +1,38 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import { registerBarTools } from "@/lib/mcp/tools/bar" +import { registerChatGptTools } from "@/lib/mcp/tools/chatgpt" +import { registerDrinkTools } from "@/lib/mcp/tools/drinks" +import { registerMetaTools } from "@/lib/mcp/tools/meta" +import { registerRecipeTools } from "@/lib/mcp/tools/recipes" +import { registerWishlistTools } from "@/lib/mcp/tools/wishlist" + +/** + * Builds the tool surface. + * + * Deliberately excluded: everything that reaches the Switchboard gateway (menu + * scanning, bartender suggestions, recommendations, AI search, photo identify, + * barcode lookup). Claude and ChatGPT are language models already - they can + * reason about a bar inventory without the app paying to do it a second time, + * and a remote client looping an expensive vision call is not a failure mode + * worth having. Also excluded: account deletion, backup restore, gateway key + * management, everything under /api/admin, and shared-list creation, which mints + * a public internet URL and should stay a deliberate human act. + * + * A note on scopes: createMcpHandler's initializer runs without a request, so a + * stateless handler cannot vary the registered tool list per token. Every tool is + * always listed; a write tool called with a read-only token returns an error + * result. Slightly wasteful in listing tokens, but honest about what exists. + */ +export function registerTools(server: McpServer): void { + registerDrinkTools(server) + registerBarTools(server) + registerRecipeTools(server) + registerWishlistTools(server) + registerMetaTools(server) + + // Only ChatGPT's deep-research mode needs these, and their generic names cost + // tool-selection clarity elsewhere. Set MCP_CHATGPT_TOOLS=0 to drop them. + if (process.env.MCP_CHATGPT_TOOLS !== "0") { + registerChatGptTools(server) + } +} diff --git a/src/lib/mcp/tokens.ts b/src/lib/mcp/tokens.ts new file mode 100644 index 0000000..d1cf238 --- /dev/null +++ b/src/lib/mcp/tokens.ts @@ -0,0 +1,50 @@ +import { createHash, randomBytes } from "crypto" + +/** + * MCP bearer tokens. + * + * Stored as a SHA-256 hash, unlike Invite.token and PasswordReset.token which are + * plaintext. Those are single-use and short-lived and the worst case is one + * unwanted signup; this one is long-lived and grants read/write over a user's + * whole collection, and the nightly pg_dump keeps 14 days of history. + * + * SHA-256 rather than bcrypt: the secret is already 256 bits of CSPRNG output, so + * there is nothing to slow an attacker down, and a bcrypt column cannot be indexed + * - verification would become a full table scan on every single MCP request. + * Not `encrypt()` from src/lib/encryption.ts either: that is reversible AES, which + * is right for an outbound key you must replay to a gateway and wrong for an + * inbound credential you only ever compare. + */ + +export const MCP_TOKEN_PREFIX = "dtk_" + +/** 32 random bytes as base64url is always 43 characters. */ +const TOKEN_RE = /^dtk_[A-Za-z0-9_-]{43}$/ + +export interface GeneratedToken { + /** The full secret. Shown to the user once and never stored. */ + raw: string + /** SHA-256 hex of `raw`. This is what goes in the database. */ + hash: string + /** First 8 characters of the random part, so the UI can tell two tokens apart. */ + prefix: string +} + +export function generateMcpToken(): GeneratedToken { + const secret = randomBytes(32).toString("base64url") + const raw = `${MCP_TOKEN_PREFIX}${secret}` + return { raw, hash: hashMcpToken(raw), prefix: secret.slice(0, 8) } +} + +export function hashMcpToken(raw: string): string { + return createHash("sha256").update(raw).digest("hex") +} + +/** + * Shape check before any database round trip, the same guard `isValidInviteToken` + * applies in src/lib/invites.ts. A garbage Authorization header - a stale cookie, + * a scanner, a client sending the wrong credential - should cost zero queries. + */ +export function looksLikeMcpToken(raw: string | undefined | null): raw is string { + return typeof raw === "string" && TOKEN_RE.test(raw) +} diff --git a/src/lib/mcp/tools/bar.ts b/src/lib/mcp/tools/bar.ts new file mode 100644 index 0000000..055a8da --- /dev/null +++ b/src/lib/mcp/tools/bar.ts @@ -0,0 +1,118 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import type { Prisma } from "@prisma/client" +import { prisma } from "@/lib/prisma" +import { deleteImagesByUrl } from "@/lib/images" +import { defineTool } from "@/lib/mcp/define" +import { McpToolError } from "@/lib/mcp/context" +import { + deleteBarItemSchema, + listBarItemsSchema, + upsertBarItemSchema, +} from "@/lib/mcp/schemas" +import { formatBarItemLine, ok } from "@/lib/mcp/render" + +/** Bar inventory - the bottles on hand, which is what recipe availability is computed from. */ +export function registerBarTools(server: McpServer): void { + defineTool( + server, + { + name: "list_bar_items", + title: "List bar inventory", + description: + "Everything in the user's home bar, grouped by category, with how much is left of each. Use this to answer what they have on hand; use list_recipes when the question is what they can make.", + inputSchema: listBarItemsSchema, + scope: "bar:read", + readOnly: true, + }, + async ({ category, includeEmpty }, caller) => { + const where: Prisma.BarItemWhereInput = { userId: caller.userId } + if (category) where.category = category + if (!includeEmpty) where.quantity = { not: "EMPTY" } + + const items = await prisma.barItem.findMany({ + where, + orderBy: [{ category: "asc" }, { name: "asc" }], + }) + + const text = items.length + ? [...items.map(formatBarItemLine), `${items.length} items`].join("\n") + : "The bar is empty." + + return ok(text, { + items: items.map((i) => ({ + id: i.id, + name: i.name, + category: i.category, + quantity: i.quantity, + notes: i.notes, + hasImage: !!i.imageUrl, + })), + total: items.length, + }) + } + ) + + defineTool( + server, + { + name: "upsert_bar_item", + title: "Add or update a bottle", + description: + "Add a bottle to the bar, or update one that is already there. Omit id to add; pass the id from list_bar_items to update. Set quantity to EMPTY when something runs out rather than deleting it.", + inputSchema: upsertBarItemSchema, + scope: "bar:write", + }, + async ({ id, ...fields }, caller) => { + if (id) { + const existing = await prisma.barItem.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true }, + }) + if (!existing) + throw new McpToolError("No bar item with that id.", "not_found") + + const item = await prisma.barItem.update({ where: { id }, data: fields }) + return { + result: ok(`Updated ${formatBarItemLine(item)}`, { id: item.id }), + recordId: item.id, + } + } + + const item = await prisma.barItem.create({ + data: { ...fields, userId: caller.userId }, + }) + return { + result: ok(`Added ${formatBarItemLine(item)}`, { id: item.id }), + recordId: item.id, + } + } + ) + + defineTool( + server, + { + name: "delete_bar_item", + title: "Remove a bottle", + description: + "Permanently remove a bottle from the bar. To record that something ran out but is usually stocked, set its quantity to EMPTY with upsert_bar_item instead.", + inputSchema: deleteBarItemSchema, + scope: "bar:write", + destructive: true, + }, + async ({ id }, caller) => { + const item = await prisma.barItem.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true, name: true, imageUrl: true }, + }) + if (!item) throw new McpToolError("No bar item with that id.", "not_found") + + await prisma.barItem.delete({ where: { id } }) + await deleteImagesByUrl([item.imageUrl]) + + return { + result: ok(`Removed ${item.name} from the bar.`, { id: item.id }), + recordId: item.id, + } + } + ) +} diff --git a/src/lib/mcp/tools/chatgpt.ts b/src/lib/mcp/tools/chatgpt.ts new file mode 100644 index 0000000..d7f19b2 --- /dev/null +++ b/src/lib/mcp/tools/chatgpt.ts @@ -0,0 +1,130 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import { prisma } from "@/lib/prisma" +import { defineTool } from "@/lib/mcp/define" +import { McpToolError } from "@/lib/mcp/context" +import { chatgptFetchSchema, chatgptSearchSchema } from "@/lib/mcp/schemas" +import { mcpBaseUrl } from "@/lib/mcp/config" +import { ok } from "@/lib/mcp/render" + +/** + * ChatGPT deep-research compatibility. + * + * That mode requires two tools named exactly `search` and `fetch` returning a + * specific shape. They are not needed for ordinary connectors, and their generic + * names can muddy tool selection when several connectors are attached at once - + * hence the aggressively specific descriptions, and the MCP_CHATGPT_TOOLS escape + * hatch in server.ts for a claude.ai-only deployment. + */ +export function registerChatGptTools(server: McpServer): void { + defineTool( + server, + { + name: "search", + title: "Search the drink collection", + description: + "Search THIS USER'S TRACKED DRINK COLLECTION in DrinkTracker - beers, wines, spirits and cocktails they have personally logged, plus their bar inventory and saved recipes. Not a web search. Returns ids for the fetch tool.", + inputSchema: chatgptSearchSchema, + scope: "drinks:read", + readOnly: true, + }, + async ({ query }, caller) => { + const drinks = await prisma.drink.findMany({ + where: { + userId: caller.userId, + OR: [ + { name: { contains: query, mode: "insensitive" } }, + { brewery: { contains: query, mode: "insensitive" } }, + { subType: { contains: query, mode: "insensitive" } }, + { region: { contains: query, mode: "insensitive" } }, + ], + }, + take: 20, + orderBy: { createdAt: "desc" }, + include: { ratings: { select: { score: true } } }, + }) + + const results = drinks.map((d) => { + const scores = d.ratings.map((r) => r.score) + const avg = scores.length + ? (scores.reduce((s, n) => s + n, 0) / scores.length).toFixed(1) + : null + return { + id: d.id, + title: d.name, + url: `${mcpBaseUrl()}/drinks/${d.id}`, + text: [ + d.type, + d.subType, + d.brewery, + d.region, + typeof d.abv === "number" ? `${d.abv}% ABV` : null, + avg ? `rated ${avg}/5` : "unrated", + d.description, + ] + .filter(Boolean) + .join(" · "), + } + }) + + return ok( + results.length + ? results.map((r) => `[${r.id}] ${r.title} — ${r.text}`).join("\n") + : "No matching drinks.", + { results } + ) + } + ) + + defineTool( + server, + { + name: "fetch", + title: "Fetch a drink record", + description: + "Retrieve the full DrinkTracker record for one drink by the id returned from the search tool, including every rating the user left for it.", + inputSchema: chatgptFetchSchema, + scope: "drinks:read", + readOnly: true, + }, + async ({ id }, caller) => { + const drink = await prisma.drink.findFirst({ + where: { id, userId: caller.userId }, + include: { ratings: { orderBy: { createdAt: "desc" } } }, + }) + if (!drink) throw new McpToolError("No drink with that id.", "not_found") + + const body = [ + `${drink.name} (${drink.type}${drink.subType ? ` / ${drink.subType}` : ""})`, + drink.brewery ? `Producer: ${drink.brewery}` : null, + drink.region ? `Region: ${drink.region}` : null, + typeof drink.abv === "number" ? `ABV: ${drink.abv}%` : null, + drink.description, + drink.ratings.length + ? `Ratings:\n${drink.ratings + .map( + (r) => + `- ${r.score}/5 on ${r.createdAt.toISOString().slice(0, 10)}${ + r.location ? ` at ${r.location}` : "" + }${r.notes ? `: ${r.notes}` : ""}` + ) + .join("\n")}` + : "No ratings recorded.", + ] + .filter(Boolean) + .join("\n") + + return ok(body, { + id: drink.id, + title: drink.name, + text: body, + url: `${mcpBaseUrl()}/drinks/${drink.id}`, + metadata: { + type: drink.type, + brewery: drink.brewery, + abv: drink.abv, + ratingCount: drink.ratings.length, + }, + }) + } + ) +} diff --git a/src/lib/mcp/tools/drinks.ts b/src/lib/mcp/tools/drinks.ts new file mode 100644 index 0000000..b30eae5 --- /dev/null +++ b/src/lib/mcp/tools/drinks.ts @@ -0,0 +1,445 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import type { Prisma } from "@prisma/client" +import { prisma } from "@/lib/prisma" +import { deleteImagesByUrl } from "@/lib/images" +import { defineTool } from "@/lib/mcp/define" +import { McpToolError } from "@/lib/mcp/context" +import { + createDrinkSchema, + deleteDrinkSchema, + emptySchema, + getDrinkSchema, + listDrinksSchema, + listRatingsSchema, + rateDrinkSchema, + updateDrinkSchema, + updateRatingSchema, +} from "@/lib/mcp/schemas" +import { + formatDrinkLine, + formatRatingLine, + ok, + paginationTrailer, +} from "@/lib/mcp/render" + +/** + * Drinks and ratings - the collection and the journal. + * + * Ownership is always `findFirst({ id, userId })` resolving to "not found", + * rather than the 404/403 split some REST routes use. A 403 confirms that a row + * exists and belongs to someone else, which is information this surface has no + * reason to hand out. + */ +export function registerDrinkTools(server: McpServer): void { + defineTool( + server, + { + name: "list_drinks", + title: "List drinks", + description: + "Search and page through the connected user's tracked drinks, each with its average rating. Use this to answer questions about what they have tried. Returns ids usable with get_drink, update_drink, rate_drink and delete_drink.", + inputSchema: listDrinksSchema, + scope: "drinks:read", + readOnly: true, + }, + async ({ search, type, sort, page, limit }, caller) => { + const where: Prisma.DrinkWhereInput = { userId: caller.userId } + + if (search) { + where.OR = [ + { name: { contains: search, mode: "insensitive" } }, + { brewery: { contains: search, mode: "insensitive" } }, + { subType: { contains: search, mode: "insensitive" } }, + { region: { contains: search, mode: "insensitive" } }, + ] + } + if (type) where.type = type + + let orderBy: Prisma.DrinkOrderByWithRelationInput = { createdAt: "desc" } + if (sort === "name") orderBy = { name: "asc" } + else if (sort === "rating") orderBy = { ratings: { _count: "desc" } } + + const [drinks, total] = await Promise.all([ + prisma.drink.findMany({ + where, + include: { ratings: { select: { score: true } } }, + orderBy, + skip: (page - 1) * limit, + take: limit, + }), + prisma.drink.count({ where }), + ]) + + const rows = drinks.map((d) => { + const scores = d.ratings.map((r) => r.score) + return { + id: d.id, + name: d.name, + type: d.type, + subType: d.subType, + brewery: d.brewery, + region: d.region, + abv: d.abv, + hasImage: !!d.imageUrl, + avgRating: scores.length + ? scores.reduce((sum, s) => sum + s, 0) / scores.length + : null, + ratingCount: scores.length, + } + }) + + // Prisma orders by rating count, not average, so the average sort is + // finished in memory - same as GET /api/drinks. + if (sort === "rating") { + rows.sort((a, b) => { + if (a.avgRating === null && b.avgRating === null) return 0 + if (a.avgRating === null) return 1 + if (b.avgRating === null) return -1 + return b.avgRating - a.avgRating + }) + } + + const text = [ + ...rows.map(formatDrinkLine), + paginationTrailer(page, limit, total), + ].join("\n") + + return ok(text, { drinks: rows, page, limit, total }) + } + ) + + defineTool( + server, + { + name: "get_drink", + title: "Get a drink", + description: + "Full detail for one drink including its description and every rating the user has left for it. Prefer list_drinks when looking across the collection.", + inputSchema: getDrinkSchema, + scope: "drinks:read", + readOnly: true, + }, + async ({ id }, caller) => { + const drink = await prisma.drink.findFirst({ + where: { id, userId: caller.userId }, + include: { ratings: { orderBy: { createdAt: "desc" } } }, + }) + if (!drink) throw new McpToolError("No drink with that id.", "not_found") + + const scores = drink.ratings.map((r) => r.score) + const avgRating = scores.length + ? scores.reduce((sum, s) => sum + s, 0) / scores.length + : null + + const header = formatDrinkLine({ ...drink, avgRating, ratingCount: scores.length }) + const lines = [header] + if (drink.description) lines.push(`description: ${drink.description}`) + if (drink.imageUrl) lines.push("has a photo (not retrievable over MCP)") + if (drink.ratings.length) { + lines.push("ratings:") + lines.push( + ...drink.ratings.map((r) => ` ${formatRatingLine({ ...r, drink })}`) + ) + } else { + lines.push("no ratings yet") + } + + return ok(lines.join("\n"), { + drink: { + id: drink.id, + name: drink.name, + type: drink.type, + subType: drink.subType, + brewery: drink.brewery, + region: drink.region, + abv: drink.abv, + description: drink.description, + hasImage: !!drink.imageUrl, + avgRating, + ratingCount: scores.length, + ratings: drink.ratings.map((r) => ({ + id: r.id, + score: r.score, + notes: r.notes, + wouldReorder: r.wouldReorder, + location: r.location, + createdAt: r.createdAt.toISOString(), + })), + }, + }) + } + ) + + defineTool( + server, + { + name: "create_drink", + title: "Add a drink", + description: + "Add a drink to the user's collection. Use rate_drink afterwards to record what they thought of it.", + inputSchema: createDrinkSchema, + scope: "drinks:write", + }, + async (input, caller) => { + const drink = await prisma.drink.create({ + data: { ...input, userId: caller.userId }, + }) + return { + result: ok(`Added ${formatDrinkLine(drink)}`, { id: drink.id }), + recordId: drink.id, + } + } + ) + + defineTool( + server, + { + name: "update_drink", + title: "Update a drink", + description: + "Change fields on an existing drink. Only the fields you pass are modified.", + inputSchema: updateDrinkSchema, + scope: "drinks:write", + }, + async ({ id, ...changes }, caller) => { + const existing = await prisma.drink.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true }, + }) + if (!existing) throw new McpToolError("No drink with that id.", "not_found") + + const drink = await prisma.drink.update({ where: { id }, data: changes }) + return { + result: ok(`Updated ${formatDrinkLine(drink)}`, { id: drink.id }), + recordId: drink.id, + } + } + ) + + defineTool( + server, + { + name: "delete_drink", + title: "Delete a drink", + description: + "Permanently remove a drink and every rating attached to it. This cannot be undone.", + inputSchema: deleteDrinkSchema, + scope: "drinks:write", + destructive: true, + }, + async ({ id }, caller) => { + const drink = await prisma.drink.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true, name: true, imageUrl: true }, + }) + if (!drink) throw new McpToolError("No drink with that id.", "not_found") + + await prisma.drink.delete({ where: { id } }) + // Best effort and after the row is gone, matching DELETE /api/drinks/[id]. + await deleteImagesByUrl([drink.imageUrl]) + + return { + result: ok(`Deleted ${drink.name}.`, { id: drink.id }), + recordId: drink.id, + } + } + ) + + defineTool( + server, + { + name: "list_ratings", + title: "List ratings", + description: + "The user's ratings, most recent first by default. Pass drinkId to see the history for one drink.", + inputSchema: listRatingsSchema, + scope: "drinks:read", + readOnly: true, + }, + async ({ drinkId, sort, page, limit }, caller) => { + const where: Prisma.RatingWhereInput = { userId: caller.userId } + if (drinkId) where.drinkId = drinkId + + const orderBy: Prisma.RatingOrderByWithRelationInput = + sort === "score-high" + ? { score: "desc" } + : sort === "score-low" + ? { score: "asc" } + : { createdAt: "desc" } + + const [ratings, total] = await Promise.all([ + prisma.rating.findMany({ + where, + orderBy, + skip: (page - 1) * limit, + take: limit, + include: { drink: { select: { name: true } } }, + }), + prisma.rating.count({ where }), + ]) + + const text = [ + ...ratings.map(formatRatingLine), + paginationTrailer(page, limit, total), + ].join("\n") + + return ok(text, { + ratings: ratings.map((r) => ({ + id: r.id, + drinkId: r.drinkId, + drinkName: r.drink.name, + score: r.score, + notes: r.notes, + wouldReorder: r.wouldReorder, + location: r.location, + createdAt: r.createdAt.toISOString(), + })), + page, + limit, + total, + }) + } + ) + + defineTool( + server, + { + name: "rate_drink", + title: "Rate a drink", + description: + "Record a 1-5 star rating for a drink the user already has, optionally with tasting notes and where they had it.", + inputSchema: rateDrinkSchema, + scope: "drinks:write", + }, + async (input, caller) => { + // The drink id arrives from the model. Without this the rating would be + // written against someone else's drink - the same check POST /api/ratings + // performs for the web app. + const drink = await prisma.drink.findFirst({ + where: { id: input.drinkId, userId: caller.userId }, + select: { id: true, name: true }, + }) + if (!drink) throw new McpToolError("No drink with that id.", "not_found") + + const rating = await prisma.rating.create({ + data: { ...input, userId: caller.userId }, + }) + + return { + result: ok(`Rated ${drink.name} ${rating.score}/5.`, { id: rating.id }), + recordId: rating.id, + } + } + ) + + defineTool( + server, + { + name: "update_rating", + title: "Update a rating", + description: + "Change the score, notes, location or would-reorder flag on an existing rating.", + inputSchema: updateRatingSchema, + scope: "drinks:write", + }, + async ({ id, ...changes }, caller) => { + const existing = await prisma.rating.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true }, + }) + if (!existing) throw new McpToolError("No rating with that id.", "not_found") + + const rating = await prisma.rating.update({ + where: { id }, + data: changes, + include: { drink: { select: { name: true } } }, + }) + + return { + result: ok( + `Updated the rating for ${rating.drink.name} (now ${rating.score}/5).`, + { id: rating.id } + ), + recordId: rating.id, + } + } + ) + + defineTool( + server, + { + name: "get_collection_stats", + title: "Collection summary", + description: + "Counts and averages across the whole collection: drinks by type, rating activity, top rated drinks, bar size and recipe count. Prefer this over several list calls when the question is about the collection as a whole.", + inputSchema: emptySchema, + scope: "drinks:read", + readOnly: true, + }, + async (_args, caller) => { + const userId = caller.userId + const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000) + + const [byType, drinkCount, ratingAgg, recentRatings, barCount, recipeCount, top] = + await Promise.all([ + prisma.drink.groupBy({ + by: ["type"], + where: { userId }, + _count: { _all: true }, + }), + prisma.drink.count({ where: { userId } }), + prisma.rating.aggregate({ + where: { userId }, + _avg: { score: true }, + _count: { _all: true }, + }), + prisma.rating.count({ + where: { userId, createdAt: { gte: thirtyDaysAgo } }, + }), + prisma.barItem.count({ where: { userId, quantity: { not: "EMPTY" } } }), + prisma.recipe.count({ where: { userId } }), + prisma.rating.findMany({ + where: { userId }, + orderBy: [{ score: "desc" }, { createdAt: "desc" }], + take: 5, + include: { drink: { select: { name: true, type: true } } }, + }), + ]) + + const typeLines = byType + .map((t) => ` ${t.type}: ${t._count._all}`) + .join("\n") + const avg = ratingAgg._avg.score + const topLines = top + .map((r) => ` ★${r.score} ${r.drink.name} (${r.drink.type})`) + .join("\n") + + const text = [ + `${drinkCount} drinks tracked`, + typeLines || " (none)", + `${ratingAgg._count._all} ratings, average ${avg ? avg.toFixed(2) : "n/a"}`, + `${recentRatings} ratings in the last 30 days`, + `${barCount} bottles in the bar, ${recipeCount} saved recipes`, + top.length ? "top rated:" : "", + topLines, + ] + .filter(Boolean) + .join("\n") + + return ok(text, { + drinkCount, + byType: Object.fromEntries(byType.map((t) => [t.type, t._count._all])), + ratingCount: ratingAgg._count._all, + averageScore: avg, + ratingsLast30Days: recentRatings, + barItemCount: barCount, + recipeCount, + topRated: top.map((r) => ({ + drinkName: r.drink.name, + type: r.drink.type, + score: r.score, + })), + }) + } + ) +} diff --git a/src/lib/mcp/tools/meta.ts b/src/lib/mcp/tools/meta.ts new file mode 100644 index 0000000..b4367c8 --- /dev/null +++ b/src/lib/mcp/tools/meta.ts @@ -0,0 +1,73 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import { prisma } from "@/lib/prisma" +import { defineTool } from "@/lib/mcp/define" +import { emptySchema } from "@/lib/mcp/schemas" +import { ok } from "@/lib/mcp/render" + +/** + * Taste context. + * + * Read-only on purpose. The flavour profile is generated by the app's own AI + * pipeline, and MCP deliberately exposes no tool that spends gateway budget - + * a remote client can read the profile, but cannot make the app pay to + * regenerate it. + */ +export function registerMetaTools(server: McpServer): void { + defineTool( + server, + { + name: "get_preferences", + title: "Get taste preferences", + description: + "The user's stated style preferences and ABV range, plus the flavour profile the app generated from their ratings. Read this before recommending anything so suggestions match their actual taste.", + inputSchema: emptySchema, + scope: "drinks:read", + readOnly: true, + }, + async (_args, caller) => { + const [prefs, profile, ratingCount] = await Promise.all([ + prisma.userPreference.findUnique({ where: { userId: caller.userId } }), + prisma.flavorProfile.findUnique({ where: { userId: caller.userId } }), + prisma.rating.count({ where: { userId: caller.userId } }), + ]) + + const lines: string[] = [] + + if (prefs?.preferredStyles.length) + lines.push(`prefers: ${prefs.preferredStyles.join(", ")}`) + if (prefs?.avoidedStyles.length) + lines.push(`avoids: ${prefs.avoidedStyles.join(", ")}`) + if (prefs?.minAbv != null || prefs?.maxAbv != null) { + lines.push( + `abv range: ${prefs.minAbv ?? "any"} to ${prefs.maxAbv ?? "any"}` + ) + } + + if (profile) { + const stale = profile.ratingCount < ratingCount + lines.push("") + lines.push( + `flavour profile (generated from ${profile.ratingCount} ratings${ + stale ? `, now ${ratingCount} - somewhat out of date` : "" + }):` + ) + lines.push(profile.profileText) + } else { + lines.push("") + lines.push( + `No flavour profile yet - the app generates one from rating history (${ratingCount} ratings so far).` + ) + } + + return ok(lines.join("\n") || "No preferences set.", { + preferredStyles: prefs?.preferredStyles ?? [], + avoidedStyles: prefs?.avoidedStyles ?? [], + minAbv: prefs?.minAbv ?? null, + maxAbv: prefs?.maxAbv ?? null, + flavorProfile: profile?.profileText ?? null, + flavorProfileRatingCount: profile?.ratingCount ?? null, + currentRatingCount: ratingCount, + }) + } + ) +} diff --git a/src/lib/mcp/tools/recipes.ts b/src/lib/mcp/tools/recipes.ts new file mode 100644 index 0000000..2e39b7a --- /dev/null +++ b/src/lib/mcp/tools/recipes.ts @@ -0,0 +1,159 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import type { Prisma } from "@prisma/client" +import { prisma } from "@/lib/prisma" +import { + fuzzyMatchIngredients, + recalculateMissingCount, +} from "@/lib/ingredient-matcher" +import { defineTool } from "@/lib/mcp/define" +import { McpToolError } from "@/lib/mcp/context" +import { + deleteRecipeSchema, + listRecipesSchema, + saveRecipeSchema, +} from "@/lib/mcp/schemas" +import { formatRecipeLine, ok } from "@/lib/mcp/render" + +type StoredIngredient = { name: string; amount: string; available: boolean } + +/** + * Saved recipes, with availability recomputed against the live bar on every read + * - the same thing GET /api/recipes does. The stored `available` flag is a + * snapshot from whenever the recipe was saved, so trusting it would answer "what + * can I make" with what was true weeks ago. + */ +export function registerRecipeTools(server: McpServer): void { + defineTool( + server, + { + name: "list_recipes", + title: "List recipes", + description: + "The user's saved cocktail recipes, with ingredient availability recomputed live against their current bar inventory. Set makeableOnly to true to answer what they can make right now. Prefer this over list_bar_items when the question is about drinks rather than bottles.", + inputSchema: listRecipesSchema, + scope: "bar:read", + readOnly: true, + }, + async ({ makeableOnly, search }, caller) => { + const where: Prisma.RecipeWhereInput = { userId: caller.userId } + if (search) where.title = { contains: search, mode: "insensitive" } + + const [recipes, barItems] = await Promise.all([ + prisma.recipe.findMany({ + where, + orderBy: { createdAt: "desc" }, + include: { sourceDrink: { select: { name: true } } }, + }), + prisma.barItem.findMany({ + where: { userId: caller.userId, quantity: { not: "EMPTY" } }, + select: { name: true }, + }), + ]) + + const processed = recipes.map((recipe) => { + const stored = Array.isArray(recipe.ingredients) + ? (recipe.ingredients as unknown as StoredIngredient[]) + : [] + const ingredients = barItems.length + ? fuzzyMatchIngredients(stored, barItems) + : stored + return { + id: recipe.id, + title: recipe.title, + ingredients, + missingCount: recalculateMissingCount(ingredients), + steps: Array.isArray(recipe.steps) ? (recipe.steps as string[]) : [], + garnish: recipe.garnish, + glassware: recipe.glassware, + notes: recipe.notes, + sourceDrinkName: recipe.sourceDrink?.name ?? null, + } + }) + + const visible = makeableOnly + ? processed.filter((r) => r.missingCount === 0) + : processed + + const text = visible.length + ? [ + ...visible.map(formatRecipeLine), + `${visible.length} of ${processed.length} recipes${ + makeableOnly ? " can be made right now" : "" + }`, + ].join("\n") + : makeableOnly + ? "Nothing can be made from the current bar inventory." + : "No saved recipes." + + return ok(text, { recipes: visible, total: processed.length }) + } + ) + + defineTool( + server, + { + name: "save_recipe", + title: "Save a recipe", + description: + "Save a cocktail recipe. Mark each ingredient available true or false as best you can; availability is recomputed against the live bar whenever the recipe is read, so a wrong guess here is self-correcting.", + inputSchema: saveRecipeSchema, + scope: "bar:write", + }, + async (input, caller) => { + // sourceDrinkId is a foreign key onto Drink supplied by the caller. Without + // this check a recipe could be attached to someone else's drink, where it + // would render on their page and they could not remove it. + if (input.sourceDrinkId) { + const ownsDrink = await prisma.drink.findFirst({ + where: { id: input.sourceDrinkId, userId: caller.userId }, + select: { id: true }, + }) + if (!ownsDrink) + throw new McpToolError("No drink with that id.", "not_found") + } + + const recipe = await prisma.recipe.create({ + data: { + userId: caller.userId, + title: input.title, + ingredients: input.ingredients as unknown as Prisma.InputJsonValue, + steps: input.steps as unknown as Prisma.InputJsonValue, + garnish: input.garnish || null, + glassware: input.glassware || null, + sourceDrinkId: input.sourceDrinkId || null, + notes: input.notes || null, + }, + }) + + return { + result: ok(`Saved recipe "${recipe.title}".`, { id: recipe.id }), + recordId: recipe.id, + } + } + ) + + defineTool( + server, + { + name: "delete_recipe", + title: "Delete a recipe", + description: "Permanently remove a saved recipe.", + inputSchema: deleteRecipeSchema, + scope: "bar:write", + destructive: true, + }, + async ({ id }, caller) => { + const recipe = await prisma.recipe.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true, title: true }, + }) + if (!recipe) throw new McpToolError("No recipe with that id.", "not_found") + + await prisma.recipe.delete({ where: { id } }) + return { + result: ok(`Deleted recipe "${recipe.title}".`, { id: recipe.id }), + recordId: recipe.id, + } + } + ) +} diff --git a/src/lib/mcp/tools/wishlist.ts b/src/lib/mcp/tools/wishlist.ts new file mode 100644 index 0000000..e9305a0 --- /dev/null +++ b/src/lib/mcp/tools/wishlist.ts @@ -0,0 +1,146 @@ +import type { McpServer } from "@modelcontextprotocol/server" +import { prisma } from "@/lib/prisma" +import { defineTool } from "@/lib/mcp/define" +import { McpToolError } from "@/lib/mcp/context" +import { + addWishlistItemSchema, + listWishlistSchema, + promoteWishlistItemSchema, + removeWishlistItemSchema, +} from "@/lib/mcp/schemas" +import { formatWishlistLine, ok } from "@/lib/mcp/render" + +/** Things the user wants to try but has not yet. */ +export function registerWishlistTools(server: McpServer): void { + defineTool( + server, + { + name: "list_wishlist", + title: "List wishlist", + description: + "Drinks the user wants to try but has not tracked yet. Use promote_wishlist_item once they have actually had one.", + inputSchema: listWishlistSchema, + scope: "drinks:read", + readOnly: true, + }, + async (_args, caller) => { + const items = await prisma.wishlistItem.findMany({ + where: { userId: caller.userId }, + orderBy: { createdAt: "desc" }, + }) + + const text = items.length + ? [...items.map(formatWishlistLine), `${items.length} items`].join("\n") + : "The wishlist is empty." + + return ok(text, { + items: items.map((i) => ({ + id: i.id, + name: i.name, + type: i.type, + subType: i.subType, + brewery: i.brewery, + abv: i.abv, + notes: i.notes, + source: i.source, + })), + total: items.length, + }) + } + ) + + defineTool( + server, + { + name: "add_wishlist_item", + title: "Add to wishlist", + description: + "Note a drink the user wants to try later. Use create_drink instead if they have already had it.", + inputSchema: addWishlistItemSchema, + scope: "drinks:write", + }, + async (input, caller) => { + const item = await prisma.wishlistItem.create({ + // source is set here rather than accepted from the caller, so entries + // added this way stay attributable the way scan and ai_search ones are. + data: { ...input, source: "mcp", userId: caller.userId }, + }) + return { + result: ok(`Added ${item.name} to the wishlist.`, { id: item.id }), + recordId: item.id, + } + } + ) + + defineTool( + server, + { + name: "remove_wishlist_item", + title: "Remove from wishlist", + description: + "Drop a wishlist entry without tracking it. To move it into the collection instead, use promote_wishlist_item.", + inputSchema: removeWishlistItemSchema, + scope: "drinks:write", + destructive: true, + }, + async ({ id }, caller) => { + const item = await prisma.wishlistItem.findFirst({ + where: { id, userId: caller.userId }, + select: { id: true, name: true }, + }) + if (!item) + throw new McpToolError("No wishlist item with that id.", "not_found") + + await prisma.wishlistItem.delete({ where: { id } }) + return { + result: ok(`Removed ${item.name} from the wishlist.`, { id: item.id }), + recordId: item.id, + } + } + ) + + defineTool( + server, + { + name: "promote_wishlist_item", + title: "Move a wishlist item into the collection", + description: + "Turn a wishlist entry into a tracked drink once the user has actually tried it, removing it from the wishlist. Follow with rate_drink to record what they thought.", + inputSchema: promoteWishlistItemSchema, + scope: "drinks:write", + }, + async ({ id }, caller) => { + const item = await prisma.wishlistItem.findFirst({ + where: { id, userId: caller.userId }, + }) + if (!item) + throw new McpToolError("No wishlist item with that id.", "not_found") + + // One transaction so a failure cannot leave the entry on both lists, or + // on neither. + const drink = await prisma.$transaction(async (tx) => { + const created = await tx.drink.create({ + data: { + userId: caller.userId, + name: item.name, + type: item.type, + subType: item.subType, + brewery: item.brewery, + abv: item.abv, + description: item.description, + }, + }) + await tx.wishlistItem.delete({ where: { id: item.id } }) + return created + }) + + return { + result: ok( + `Moved ${drink.name} from the wishlist into the collection.`, + { id: drink.id } + ), + recordId: drink.id, + } + } + ) +}