Compare commits

..

2 Commits

Author SHA1 Message Date
JP
e77f605c9c Add OAuth 2.1 server so claude.ai and ChatGPT can connect natively
Phase A needed a token pasted into a header, which Anthropic documents as an
org-admin-scoped beta on claude.ai and is undocumented on ChatGPT. This makes
the app its own authorization server so both connect through their normal
"add a connector" flow, with a per-user consent screen.

The whole thing funnels into the existing verifyMcpToken: an issued access
token is an ordinary McpAccessToken row with source "oauth", so the resource
server gained no OAuth awareness and Phase A's verification path is unchanged.

Notes on the parts that fail quietly if got wrong:

- scopes_supported is published in the protected resource metadata. When a 401
  challenge carries no explicit scope Claude requests exactly what is
  advertised there, so omitting it silently makes every connection read-only.
- Loopback redirect URIs match with the port ignored. Claude Code registers
  http://localhost/callback and then redirects to an ephemeral port; exact
  matching would reject every native client. RFC 8252 7.3 requires this.
- CIMD is deliberately not advertised. Claude only selects it when the metadata
  carries client_id_metadata_document_supported, and supporting it would mean
  fetching a client-supplied URL server-side from a host that also reaches
  MinIO, Postgres and the gateway on the LAN. DCR costs nothing by comparison.
- The consent page validates client_id and redirect_uri before it will redirect
  anywhere, because an unvalidated redirect_uri is an open redirect.
- Authorization codes are consumed by one guarded updateMany, so a replay under
  concurrency cannot mint a second token. A PKCE mismatch burns the whole grant
  rather than just the code.
- Refresh tokens rotate and keep the previous hash; presenting it revokes the
  grant, since that is either theft or a client that cannot be trusted to hold
  state.

Also fixes the login page, which hardcoded callbackUrl and so dropped anyone
sent to sign in for the consent screen onto /dashboard instead. Same-origin
destinations only, absolute or relative - the middleware writes absolute.

"/.well-known" joins PUBLIC_ROUTES. It is a prefix match, so nothing else
should be served from there.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 05:33:48 +00:00
JP
4fd339dabc Add MCP server so Claude and ChatGPT can read and write drink data
Exposes the collection over the Model Context Protocol at /api/mcp, with 22
tools covering drinks, ratings, bar inventory, recipes, wishlist and taste
preferences, plus search/fetch aliases for ChatGPT's deep-research mode.

Authentication is a bearer token, the app's first header-borne credential -
every other route derives identity from the NextAuth cookie, which a machine
client cannot present. /api/mcp sits under the middleware's /api exclusion so
it can answer a JSON 401 with an RFC 9728 WWW-Authenticate challenge instead
of an HTML redirect to /login.

Tokens are stored as a SHA-256 hash rather than plaintext like Invite.token
and PasswordReset.token. Those are single-use and short-lived; this one is
long-lived and grants read/write over a whole collection, and the nightly
pg_dump keeps 14 days of history. Not encrypt(), which is reversible AES and
right only for outbound keys we must replay; not bcrypt, which cannot be
indexed and would turn verification into a table scan per request.

verifyMcpToken joins User.status on every call, mirroring the jwt callback, so
suspending a member kills their MCP access immediately rather than leaving the
token as a documented way to outlive suspension. It fails closed on a database
error, deliberately unlike the jwt callback, which keeps the session because a
throw there would sign out every user at once.

No tool reaches the Switchboard gateway. Claude and ChatGPT are language
models already, so they can reason over a bar inventory without the app paying
to do it a second time, and a remote client looping a vision call is not a
failure mode worth having. Account deletion, restore, gateway keys, admin
routes and shared-list creation are excluded too.

The OAuth models ship now but are unused; the token endpoint will write the
same McpAccessToken rows, so adding it later touches no verification code.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01W1Ee4Mc1X1SX8HgYa52zu7
2026-08-09 04:29:54 +00:00
38 changed files with 4136 additions and 2 deletions

78
package-lock.json generated
View File

@@ -10,6 +10,7 @@
"dependencies": { "dependencies": {
"@auth/prisma-adapter": "^2.11.1", "@auth/prisma-adapter": "^2.11.1",
"@aws-sdk/client-s3": "^3.1000.0", "@aws-sdk/client-s3": "^3.1000.0",
"@modelcontextprotocol/server": "^2.0.0",
"@prisma/client": "^6.19.2", "@prisma/client": "^6.19.2",
"@tanstack/react-query": "^5.90.21", "@tanstack/react-query": "^5.90.21",
"@types/bcryptjs": "^2.4.6", "@types/bcryptjs": "^2.4.6",
@@ -18,6 +19,7 @@
"clsx": "^2.1.1", "clsx": "^2.1.1",
"html5-qrcode": "^2.3.8", "html5-qrcode": "^2.3.8",
"lucide-react": "^0.575.0", "lucide-react": "^0.575.0",
"mcp-handler": "^2.1.0",
"next": "14.2.35", "next": "14.2.35",
"next-auth": "^5.0.0-beta.25", "next-auth": "^5.0.0-beta.25",
"openai": "^6.25.0", "openai": "^6.25.0",
@@ -1607,6 +1609,31 @@
"@jridgewell/sourcemap-codec": "^1.4.14" "@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": { "node_modules/@napi-rs/wasm-runtime": {
"version": "0.2.12", "version": "0.2.12",
"resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz",
@@ -6125,6 +6152,57 @@
"node": ">= 0.4" "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": { "node_modules/merge2": {
"version": "1.4.1", "version": "1.4.1",
"resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz",

View File

@@ -11,6 +11,7 @@
"dependencies": { "dependencies": {
"@auth/prisma-adapter": "^2.11.1", "@auth/prisma-adapter": "^2.11.1",
"@aws-sdk/client-s3": "^3.1000.0", "@aws-sdk/client-s3": "^3.1000.0",
"@modelcontextprotocol/server": "^2.0.0",
"@prisma/client": "^6.19.2", "@prisma/client": "^6.19.2",
"@tanstack/react-query": "^5.90.21", "@tanstack/react-query": "^5.90.21",
"@types/bcryptjs": "^2.4.6", "@types/bcryptjs": "^2.4.6",
@@ -19,6 +20,7 @@
"clsx": "^2.1.1", "clsx": "^2.1.1",
"html5-qrcode": "^2.3.8", "html5-qrcode": "^2.3.8",
"lucide-react": "^0.575.0", "lucide-react": "^0.575.0",
"mcp-handler": "^2.1.0",
"next": "14.2.35", "next": "14.2.35",
"next-auth": "^5.0.0-beta.25", "next-auth": "^5.0.0-beta.25",
"openai": "^6.25.0", "openai": "^6.25.0",

View File

@@ -58,6 +58,11 @@ model User {
invitesCreated Invite[] @relation("InviteCreator") invitesCreated Invite[] @relation("InviteCreator")
redemption InviteRedemption? redemption InviteRedemption?
passwordResets PasswordReset[] passwordResets PasswordReset[]
mcpTokens McpAccessToken[]
mcpAuditLogs McpAuditLog[]
oauthAuthCodes OAuthAuthCode[]
oauthGrants OAuthGrant[]
} }
// ─── Invites ───────────────────────────────────────────────────── // ─── Invites ─────────────────────────────────────────────────────
@@ -111,6 +116,143 @@ model PasswordReset {
@@index([userId]) @@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 { model Account {
id String @id @default(cuid()) id String @id @default(cuid())
userId String userId String

View File

@@ -1,7 +1,8 @@
"use client" "use client"
import { useState } from "react" import { Suspense, useState } from "react"
import { signIn } from "next-auth/react" import { signIn } from "next-auth/react"
import { useSearchParams } from "next/navigation"
import Link from "next/link" import Link from "next/link"
import { Beer, Loader2 } from "lucide-react" import { Beer, Loader2 } from "lucide-react"
import { Button } from "@/components/ui/button" import { Button } from "@/components/ui/button"
@@ -9,7 +10,49 @@ import { Input } from "@/components/ui/input"
import { Label } from "@/components/ui/label" import { Label } from "@/components/ui/label"
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card" import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card"
/**
* Only same-origin destinations are honoured. Without this check the
* `?callbackUrl=` parameter - which anyone can put in a link - would make the
* login page an open redirect onto an attacker's site, wearing our domain.
*
* Both forms have to be accepted. A relative path is what /oauth/authorize
* builds, while the middleware's own redirect writes an absolute URL, and
* rejecting that one would quietly drop people on /dashboard instead of the
* consent screen they were sent to sign in for.
*
* A leading `//` is rejected because `//evil.com` is protocol-relative, which
* the browser resolves as absolute.
*/
function safeCallbackUrl(value: string | null): string {
if (!value) return "/dashboard"
if (value.startsWith("/")) {
return value.startsWith("//") ? "/dashboard" : value
}
try {
const target = new URL(value)
if (target.origin === window.location.origin) {
return `${target.pathname}${target.search}${target.hash}`
}
} catch {
// Not a URL at all.
}
return "/dashboard"
}
export default function LoginPage() { export default function LoginPage() {
// useSearchParams needs a Suspense boundary; this page prerenders statically.
return (
<Suspense fallback={null}>
<LoginForm />
</Suspense>
)
}
function LoginForm() {
const searchParams = useSearchParams()
const callbackUrl = safeCallbackUrl(searchParams.get("callbackUrl"))
const [email, setEmail] = useState("") const [email, setEmail] = useState("")
const [password, setPassword] = useState("") const [password, setPassword] = useState("")
const [error, setError] = useState("") const [error, setError] = useState("")
@@ -24,7 +67,7 @@ export default function LoginPage() {
const result = await signIn("credentials", { const result = await signIn("credentials", {
email, email,
password, password,
callbackUrl: "/dashboard", callbackUrl,
redirect: false, redirect: false,
}) })

View File

@@ -0,0 +1,65 @@
import { NextResponse } from "next/server"
import { mcpBaseUrl } from "@/lib/mcp/config"
import { SUPPORTED_SCOPES } from "@/lib/mcp/oauth"
/**
* RFC 8414 authorization server metadata.
*
* `issuer` must equal the base URL this document was discovered at, so it is
* derived from the same NEXTAUTH_URL everything else uses rather than hardcoded.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
function metadata() {
const base = mcpBaseUrl()
return {
issuer: base,
authorization_endpoint: `${base}/oauth/authorize`,
token_endpoint: `${base}/api/oauth/token`,
registration_endpoint: `${base}/api/oauth/register`,
revocation_endpoint: `${base}/api/oauth/revoke`,
response_types_supported: ["code"],
grant_types_supported: ["authorization_code", "refresh_token"],
// Claude always sends a PKCE challenge and checks that S256 is advertised
// before starting the flow. `plain` is not accepted.
code_challenge_methods_supported: ["S256"],
// Public clients only. No client secret is ever issued or stored, so there
// is none to leak from this deployment.
token_endpoint_auth_methods_supported: ["none"],
revocation_endpoint_auth_methods_supported: ["none"],
scopes_supported: SUPPORTED_SCOPES,
service_documentation: `${base}/settings`,
//
// Deliberately absent: client_id_metadata_document_supported.
//
// Claude picks CIMD only when this document advertises BOTH that flag and
// "none" in token_endpoint_auth_methods_supported; omitting it makes both
// Claude and ChatGPT fall back to dynamic registration cleanly. CIMD would
// mean fetching a client-supplied URL server-side, from a host that also
// reaches MinIO on 127.0.0.1:9000, Postgres on 5432 and the Switchboard
// gateway on the LAN. That is an SSRF pivot in exchange for nothing here;
// registration is a POST to our own endpoint with no outbound traffic.
}
}
const CORS = {
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=3600",
}
export function GET(): NextResponse {
return NextResponse.json(metadata(), { headers: CORS })
}
export function OPTIONS(): Response {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Access-Control-Max-Age": "86400",
},
})
}

View File

@@ -0,0 +1,15 @@
/**
* RFC 9728 path-inserted form of the protected resource metadata.
*
* For a resource at https://host/api/mcp, a client probes
* /.well-known/oauth-protected-resource/api/mcp before falling back to the bare
* /.well-known/oauth-protected-resource. Both are served so discovery works
* whichever a given client tries, and whether or not it read the
* WWW-Authenticate challenge that names the URL explicitly.
*/
export { GET, OPTIONS } from "../../route"
// Declared literally rather than re-exported: Next reads these statically and
// cannot follow a re-export.
export const runtime = "nodejs"
export const dynamic = "force-dynamic"

View File

@@ -0,0 +1,62 @@
import { NextResponse } from "next/server"
import { generateProtectedResourceMetadata } from "mcp-handler"
import { mcpBaseUrl, mcpResourceUrl } from "@/lib/mcp/config"
import { SUPPORTED_SCOPES } from "@/lib/mcp/oauth"
/**
* RFC 9728 protected resource metadata - how a client discovers where to
* authenticate for /api/mcp.
*
* Two constraints worth stating, because breaking either fails silently as
* "couldn't reach the MCP server":
*
* - `resource` must match the URL the user typed into their client exactly,
* which is why both it and the issuer come from NEXTAUTH_URL rather than the
* request. See src/lib/mcp/config.ts.
* - Claude reads only the FIRST entry of authorization_servers and does not
* fall back to later ones, so there is exactly one.
*
* This path sits outside /api, so it is caught by the middleware matcher and
* needs "/.well-known" in PUBLIC_ROUTES - otherwise it answers with an HTML
* redirect to /login and discovery never starts.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
/**
* `scopes_supported` is not decoration. When a client's 401 challenge carries no
* explicit scope, Claude requests exactly the scopes advertised here - so
* omitting it makes every connection fall back to the read-only default and the
* user is left wondering why the assistant cannot add a drink. The consent
* screen is what actually gates the write scopes.
*/
export function GET(): Response {
const metadata = generateProtectedResourceMetadata({
authServerUrls: [mcpBaseUrl()],
resourceUrl: mcpResourceUrl(),
additionalMetadata: {
scopes_supported: SUPPORTED_SCOPES,
resource_name: "DrinkTracker",
bearer_methods_supported: ["header"],
},
})
return NextResponse.json(metadata, {
headers: {
"Access-Control-Allow-Origin": "*",
"Cache-Control": "public, max-age=3600",
},
})
}
export function OPTIONS(): Response {
return new Response(null, {
status: 204,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET, OPTIONS",
"Access-Control-Allow-Headers": "Authorization, Content-Type",
"Access-Control-Max-Age": "86400",
},
})
}

109
src/app/api/mcp/route.ts Normal file
View File

@@ -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<string, string> = {
"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<Response> {
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 }))
}

View File

@@ -0,0 +1,102 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import {
buildRedirect,
validateAuthorizeRequest,
} from "@/lib/mcp/authorize-request"
import { AUTH_CODE_TTL_MS, generateAuthCode } from "@/lib/mcp/oauth"
/**
* The user's decision on the consent screen.
*
* Everything is re-validated from the query string rather than trusted from the
* request body: the body is just a carrier for the original parameters, and
* treating any of it as already-checked would let a crafted POST mint a code for
* a client and redirect the page never approved.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
const bodySchema = z.object({
decision: z.enum(["allow", "deny"]),
search: z.string().max(4096),
})
export async function POST(request: Request) {
const session = await requireUser()
if (session instanceof NextResponse) return session
const parsed = bodySchema.safeParse(await request.json().catch(() => null))
if (!parsed.success) {
return NextResponse.json({ error: "invalid_request" }, { status: 400 })
}
const search = new URLSearchParams(parsed.data.search)
const validation = await validateAuthorizeRequest(search)
if (validation.kind === "fatal") {
return NextResponse.json(
{ error: "invalid_request", error_description: validation.message },
{ status: 400 }
)
}
if (validation.kind === "redirectable") {
return NextResponse.json({
redirectTo: buildRedirect(validation.redirectUri, {
error: validation.error,
error_description: validation.description,
state: validation.state,
}),
})
}
const { params, client } = validation
const userId = session.user.id
if (parsed.data.decision === "deny") {
return NextResponse.json({
redirectTo: buildRedirect(params.redirectUri, {
error: "access_denied",
error_description: "The user declined the request.",
state: params.state,
}),
})
}
// One standing grant per (client, user). Re-approving widens the scopes and
// clears a previous revocation rather than piling up rows.
const grant = await prisma.oAuthGrant.upsert({
where: { clientId_userId: { clientId: client.id, userId } },
update: { scopes: params.scopes, revokedAt: null },
create: { clientId: client.id, userId, scopes: params.scopes },
select: { id: true },
})
const { code, hash } = generateAuthCode()
await prisma.oAuthAuthCode.create({
data: {
codeHash: hash,
clientId: client.id,
userId,
redirectUri: params.redirectUri,
resource: params.resource,
scopes: params.scopes,
codeChallenge: params.codeChallenge,
codeChallengeMethod: "S256",
expiresAt: new Date(Date.now() + AUTH_CODE_TTL_MS),
},
})
console.log(
`[oauth] granted user=${userId} client=${client.clientId} scopes=${params.scopes.join(",")} grant=${grant.id}`
)
return NextResponse.json({
redirectTo: buildRedirect(params.redirectUri, {
code,
state: params.state,
}),
})
}

View File

@@ -0,0 +1,142 @@
import { NextResponse } from "next/server"
import { z } from "zod"
import { prisma } from "@/lib/prisma"
import { rateLimit } from "@/lib/rate-limit"
import {
generateClientId,
isRegisterableRedirectUri,
oauthError,
} from "@/lib/mcp/oauth"
/**
* RFC 7591 dynamic client registration.
*
* Unauthenticated by specification, which makes it the one endpoint on this
* deployment that a stranger can create rows through. Hence the rate limit, the
* global cap, and the pruning of registrations that never went on to be used.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
/** Beyond this many registrations in a day, something is wrong. */
const DAILY_REGISTRATION_CAP = 500
const PRUNE_AFTER_MS = 7 * 24 * 60 * 60 * 1000
const registerSchema = z.object({
client_name: z.string().min(1).max(200).optional(),
redirect_uris: z.array(z.string().min(1)).min(1).max(10),
grant_types: z.array(z.string()).optional(),
response_types: z.array(z.string()).optional(),
token_endpoint_auth_method: z.string().optional(),
scope: z.string().max(500).optional(),
client_uri: z.string().max(2048).optional(),
logo_uri: z.string().max(2048).optional(),
software_id: z.string().max(200).optional(),
})
export async function POST(request: Request) {
const forwarded = request.headers.get("x-forwarded-for")
const hops = forwarded?.split(",").map((h) => h.trim()).filter(Boolean) ?? []
// Last hop, not first: everything before it is client-supplied and can be
// forged for a fresh bucket. Same reasoning as the register route.
const ip = hops.length > 0 ? hops[hops.length - 1] : "unknown"
const rl = rateLimit(`dcr:${ip}`, 5, 60 * 60 * 1000)
if (!rl.success) {
return oauthError(
"temporarily_unavailable",
"Too many registration attempts.",
429
)
}
const body = await request.json().catch(() => null)
if (!body) return oauthError("invalid_client_metadata", "Body must be JSON.")
const parsed = registerSchema.safeParse(body)
if (!parsed.success) {
return oauthError("invalid_client_metadata", parsed.error.issues[0]?.message)
}
const data = parsed.data
// Public clients only. Accepting a confidential client would mean storing a
// secret this server has no need for and no way to protect better than the
// PKCE it already requires.
const authMethod = data.token_endpoint_auth_method ?? "none"
if (authMethod !== "none") {
return oauthError(
"invalid_client_metadata",
"This server issues public clients only; token_endpoint_auth_method must be \"none\"."
)
}
const bad = data.redirect_uris.filter((u) => !isRegisterableRedirectUri(u))
if (bad.length) {
return oauthError(
"invalid_redirect_uri",
`Redirect URIs must be https or a loopback address, with no fragment: ${bad.join(", ")}`
)
}
const since = new Date(Date.now() - 24 * 60 * 60 * 1000)
const recent = await prisma.oAuthClient.count({
where: { createdAt: { gte: since } },
})
if (recent >= DAILY_REGISTRATION_CAP) {
return oauthError(
"temporarily_unavailable",
"Registration is temporarily closed.",
503
)
}
const clientId = generateClientId()
const client = await prisma.oAuthClient.create({
data: {
clientId,
clientName: data.client_name ?? "Unnamed client",
redirectUris: data.redirect_uris,
grantTypes: data.grant_types ?? ["authorization_code", "refresh_token"],
responseTypes: data.response_types ?? ["code"],
tokenEndpointAuthMethod: "none",
scope: data.scope ?? null,
clientUri: data.client_uri ?? null,
logoUri: data.logo_uri ?? null,
softwareId: data.software_id ?? null,
},
})
pruneUnusedClients()
return NextResponse.json(
{
client_id: client.clientId,
client_id_issued_at: Math.floor(client.createdAt.getTime() / 1000),
client_name: client.clientName,
redirect_uris: client.redirectUris,
grant_types: client.grantTypes,
response_types: client.responseTypes,
token_endpoint_auth_method: "none",
...(client.scope ? { scope: client.scope } : {}),
},
{ status: 201, headers: { "Cache-Control": "no-store" } }
)
}
/**
* Registrations that never led to a grant are abandoned handshakes. Cleared
* opportunistically rather than on a schedule, because there is no scheduler.
*/
function pruneUnusedClients(): void {
prisma.oAuthClient
.deleteMany({
where: {
createdAt: { lt: new Date(Date.now() - PRUNE_AFTER_MS) },
grants: { none: {} },
},
})
.then(({ count }) => {
if (count > 0) console.log(`[oauth] pruned ${count} unused client(s)`)
})
.catch((error) => console.warn("[oauth] client prune failed:", error))
}

View File

@@ -0,0 +1,56 @@
import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { revokeGrant, sha256 } from "@/lib/mcp/oauth"
/**
* RFC 7009 token revocation.
*
* Always answers 200, even for a token that does not exist. That is the spec's
* requirement and it is also what stops this endpoint from becoming an oracle
* for guessing valid tokens.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
export async function POST(request: Request) {
const contentType = request.headers.get("content-type") ?? ""
const form = contentType.includes("application/json")
? new URLSearchParams(
Object.entries((await request.json().catch(() => ({}))) as Record<string, unknown>)
.map(([k, v]) => [k, String(v)])
)
: new URLSearchParams(await request.text())
const token = form.get("token")
const ok = NextResponse.json({}, { headers: { "Cache-Control": "no-store" } })
if (!token) return ok
const hash = sha256(token)
try {
// A refresh token identifies the whole grant, so revoking it ends the
// connection outright.
const grant = await prisma.oAuthGrant.findFirst({
where: { OR: [{ refreshHash: hash }, { refreshPrevHash: hash }] },
select: { id: true },
})
if (grant) {
await revokeGrant(grant.id)
return ok
}
// An access token revokes only itself; the client can still refresh. That
// matches RFC 7009's guidance that revoking an access token need not
// invalidate the refresh token.
await prisma.mcpAccessToken.updateMany({
where: { tokenHash: hash, revokedAt: null },
data: { revokedAt: new Date() },
})
} catch (error) {
// Still a 200 - the caller's intent was for the token to stop working, and
// reporting an internal failure here tells them nothing useful.
console.error("[oauth] revoke failed:", error)
}
return ok
}

View File

@@ -0,0 +1,199 @@
import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import {
OFFLINE_ACCESS,
generateRefreshToken,
issueAccessToken,
oauthError,
redirectUriMatches,
revokeGrant,
sha256,
storeRefreshToken,
verifyPkce,
} from "@/lib/mcp/oauth"
/**
* RFC 6749 token endpoint.
*
* Bodies arrive as application/x-www-form-urlencoded - required by the spec and
* what Claude sends for both the initial exchange and every refresh. JSON is
* accepted as well, since some clients send it and there is no reason to be
* strict about it.
*/
export const runtime = "nodejs"
export const dynamic = "force-dynamic"
const NO_STORE = { "Cache-Control": "no-store", Pragma: "no-cache" }
async function readForm(request: Request): Promise<URLSearchParams> {
const contentType = request.headers.get("content-type") ?? ""
if (contentType.includes("application/json")) {
const body = await request.json().catch(() => ({}))
return new URLSearchParams(
Object.entries(body as Record<string, unknown>).map(([k, v]) => [k, String(v)])
)
}
return new URLSearchParams(await request.text())
}
export async function POST(request: Request) {
const form = await readForm(request)
const grantType = form.get("grant_type")
if (grantType === "authorization_code") return exchangeCode(form)
if (grantType === "refresh_token") return refresh(form)
return oauthError(
"unsupported_grant_type",
"Supported grant types are authorization_code and refresh_token."
)
}
async function exchangeCode(form: URLSearchParams) {
const code = form.get("code")
const clientId = form.get("client_id")
const redirectUri = form.get("redirect_uri")
const verifier = form.get("code_verifier")
if (!code || !clientId || !redirectUri || !verifier) {
return oauthError(
"invalid_request",
"code, client_id, redirect_uri and code_verifier are all required."
)
}
const row = await prisma.oAuthAuthCode.findUnique({
where: { codeHash: sha256(code) },
include: {
client: { select: { id: true, clientId: true, clientName: true } },
user: { select: { id: true, status: true } },
},
})
if (!row) return oauthError("invalid_grant", "Unknown or expired code.")
// Consume before verifying anything else. One guarded statement, one row
// lock: whoever wins gets count 1 and everyone else gets 0, so a replayed
// code cannot mint a second token even under concurrency. A code that fails
// verification below stays consumed, which is the intent - it has been seen.
const { count } = await prisma.oAuthAuthCode.updateMany({
where: {
codeHash: row.codeHash,
consumedAt: null,
expiresAt: { gt: new Date() },
},
data: { consumedAt: new Date() },
})
if (count !== 1) {
return oauthError("invalid_grant", "This code has already been used or has expired.")
}
if (row.client.clientId !== clientId) {
return oauthError("invalid_grant", "This code was issued to a different client.")
}
// Exact match against what was recorded at authorize time, not a fresh
// registration lookup - the pairing is what is being verified.
if (!redirectUriMatches(row.redirectUri, redirectUri)) {
return oauthError("invalid_grant", "redirect_uri does not match the authorization request.")
}
const grant = await prisma.oAuthGrant.findUnique({
where: { clientId_userId: { clientId: row.client.id, userId: row.userId } },
select: { id: true, revokedAt: true },
})
if (!grant || grant.revokedAt) {
return oauthError("invalid_grant", "This authorization is no longer valid.")
}
if (!verifyPkce(verifier, row.codeChallenge)) {
// A verifier that does not match means whoever is holding this code is
// probably not who the code was issued to. Burn the whole grant, not just
// the code.
await revokeGrant(grant.id)
console.warn(
`[oauth] PKCE mismatch for client=${row.client.clientId} user=${row.userId}; grant revoked`
)
return oauthError("invalid_grant", "PKCE verification failed.")
}
if (row.user.status !== "ACTIVE") {
return oauthError("invalid_grant", "This account is not active.")
}
const tokens = await issueAccessToken(
grant.id,
row.userId,
row.scopes,
row.client.clientName
)
// A refresh token only exists if offline_access was actually granted.
let refreshToken: string | undefined
if (row.scopes.includes(OFFLINE_ACCESS)) {
const minted = generateRefreshToken()
await storeRefreshToken(grant.id, minted.hash, null)
refreshToken = minted.token
}
console.log(
`[oauth] token issued user=${row.userId} client=${row.client.clientId} grant=${grant.id}`
)
return NextResponse.json(
{ ...tokens, ...(refreshToken ? { refresh_token: refreshToken } : {}) },
{ headers: NO_STORE }
)
}
async function refresh(form: URLSearchParams) {
const token = form.get("refresh_token")
if (!token) return oauthError("invalid_request", "refresh_token is required.")
const hash = sha256(token)
const grant = await prisma.oAuthGrant.findFirst({
where: { OR: [{ refreshHash: hash }, { refreshPrevHash: hash }] },
include: {
client: { select: { clientId: true, clientName: true } },
user: { select: { status: true } },
},
})
if (!grant) return oauthError("invalid_grant", "Unknown refresh token.")
// Presenting the previous generation means the current one was rotated out
// from under this caller - either a replay of a stolen token or a client
// holding a stale copy. Either way the safe move is to end the grant and make
// everyone re-authorize.
if (grant.refreshPrevHash === hash && grant.refreshHash !== hash) {
await revokeGrant(grant.id)
console.warn(
`[oauth] refresh token replay for client=${grant.client.clientId} user=${grant.userId}; grant revoked`
)
return oauthError("invalid_grant", "This refresh token has already been used.")
}
if (grant.revokedAt) return oauthError("invalid_grant", "This authorization was revoked.")
if (grant.refreshExpiresAt && grant.refreshExpiresAt <= new Date()) {
return oauthError("invalid_grant", "This refresh token has expired.")
}
if (grant.user.status !== "ACTIVE") {
return oauthError("invalid_grant", "This account is not active.")
}
const tokens = await issueAccessToken(
grant.id,
grant.userId,
grant.scopes,
grant.client.clientName
)
// Rotate. OAuth 2.1 requires it for public clients, and keeping the old hash
// in refreshPrevHash is what makes the replay check above possible. Done
// after the access token is minted so a failure there leaves the caller's
// existing refresh token still usable.
const next = generateRefreshToken()
await storeRefreshToken(grant.id, next.hash, hash)
return NextResponse.json(
{ ...tokens, refresh_token: next.token },
{ headers: NO_STORE }
)
}

View File

@@ -0,0 +1,27 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
import { revokeGrant } from "@/lib/mcp/oauth"
/**
* Disconnect an app. Cascades to every access token the grant issued, so the
* connection dies on the next request rather than at the end of the current
* access token's hour.
*/
export async function DELETE(
_request: Request,
{ params }: { params: { id: string } }
) {
const session = await requireUser()
if (session instanceof NextResponse) return session
// Scoped to the caller, 404 rather than 403 - the convention across the API.
const grant = await prisma.oAuthGrant.findFirst({
where: { id: params.id, userId: session.user.id, revokedAt: null },
select: { id: true },
})
if (!grant) return NextResponse.json({ error: "Not found" }, { status: 404 })
await revokeGrant(grant.id)
return NextResponse.json({ success: true })
}

View File

@@ -0,0 +1,32 @@
import { NextResponse } from "next/server"
import { requireUser } from "@/lib/authz"
import { prisma } from "@/lib/prisma"
/** Apps the user has connected through OAuth, for the Settings list. */
export async function GET() {
const session = await requireUser()
if (session instanceof NextResponse) return session
const grants = await prisma.oAuthGrant.findMany({
where: { userId: session.user.id, revokedAt: null },
orderBy: { createdAt: "desc" },
select: {
id: true,
scopes: true,
createdAt: true,
lastUsedAt: true,
client: { select: { clientName: true, clientUri: true } },
},
})
return NextResponse.json({
grants: grants.map((g) => ({
id: g.id,
clientName: g.client.clientName,
clientUri: g.client.clientUri,
scopes: g.scopes,
createdAt: g.createdAt,
lastUsedAt: g.lastUsedAt,
})),
})
}

View File

@@ -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 })
}

View File

@@ -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 }
)
}

View File

@@ -0,0 +1,183 @@
import { redirect } from "next/navigation"
import { auth } from "@/lib/auth"
import { prisma } from "@/lib/prisma"
import { Beer, ShieldCheck } from "lucide-react"
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card"
import { ConsentForm } from "@/components/oauth/consent-form"
import {
buildRedirect,
validateAuthorizeRequest,
} from "@/lib/mcp/authorize-request"
import {
AUTH_CODE_TTL_MS,
SCOPE_DESCRIPTIONS,
coversScopes,
generateAuthCode,
} from "@/lib/mcp/oauth"
/**
* The consent screen.
*
* Not in PUBLIC_ROUTES, so the middleware bounces an unauthenticated visitor to
* /login for us - and now that login honours ?callbackUrl they come straight
* back here afterwards. The explicit session check below is for the callbackUrl
* construction, not for access control.
*
* Deliberately outside the (app) route group: this is a credential prompt, and
* it should not be wrapped in the sidebar and bottom nav of the signed-in app.
*/
export const dynamic = "force-dynamic"
type SearchParams = Record<string, string | string[] | undefined>
function toParams(searchParams: SearchParams): URLSearchParams {
const params = new URLSearchParams()
for (const [key, value] of Object.entries(searchParams)) {
if (typeof value === "string") params.set(key, value)
else if (Array.isArray(value) && value[0]) params.set(key, value[0])
}
return params
}
export default async function AuthorizePage({
searchParams,
}: {
searchParams: SearchParams
}) {
const search = toParams(searchParams)
const validation = await validateAuthorizeRequest(search)
if (validation.kind === "fatal") {
return <ErrorCard title="This link isn't valid" detail={validation.message} />
}
if (validation.kind === "redirectable") {
redirect(
buildRedirect(validation.redirectUri, {
error: validation.error,
error_description: validation.description,
state: validation.state,
})
)
}
const { params, client } = validation
const session = await auth()
if (!session?.user?.id) {
redirect(`/login?callbackUrl=${encodeURIComponent(`/oauth/authorize?${search}`)}`)
}
// A session already implies an ACTIVE user - the jwt callback in lib/auth.ts
// returns null for anyone suspended or deleted, which clears the cookie.
const userId = session.user.id
// Already approved for these scopes? Skip the screen. This is what makes a
// re-connection after an expired refresh token silent rather than another
// round of clicking Allow.
const existing = await prisma.oAuthGrant.findUnique({
where: { clientId_userId: { clientId: client.id, userId } },
select: { id: true, scopes: true, revokedAt: true },
})
if (existing && !existing.revokedAt && coversScopes(existing.scopes, params.scopes)) {
const code = await createAuthCode(client.id, userId, params)
redirect(buildRedirect(params.redirectUri, { code, state: params.state }))
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<div className="flex justify-center mb-4">
<Beer className="h-10 w-10 text-primary" />
</div>
<CardTitle className="text-xl">
Connect {client.clientName} to DrinkTracker?
</CardTitle>
<CardDescription>
Signed in as {session.user.email ?? session.user.name}
</CardDescription>
</CardHeader>
<CardContent className="space-y-5">
<div className="space-y-2">
<p className="text-sm font-medium">It will be able to:</p>
<ul className="space-y-1.5">
{params.scopes.map((scope) => (
<li key={scope} className="flex gap-2 text-sm text-muted-foreground">
<ShieldCheck className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
<span>{SCOPE_DESCRIPTIONS[scope] ?? scope}</span>
</li>
))}
</ul>
</div>
{client.clientUri && (
<p className="text-xs text-muted-foreground break-all">
{client.clientUri}
</p>
)}
<p className="text-xs text-muted-foreground">
It will be sent back to <code className="break-all">{params.redirectUri}</code>.
You can disconnect it any time from Settings.
</p>
<ConsentForm search={search.toString()} />
</CardContent>
</Card>
</div>
)
}
async function createAuthCode(
clientRowId: string,
userId: string,
params: {
redirectUri: string
scopes: string[]
codeChallenge: string
resource: string | null
}
): Promise<string> {
const { code, hash } = generateAuthCode()
await prisma.oAuthAuthCode.create({
data: {
codeHash: hash,
clientId: clientRowId,
userId,
redirectUri: params.redirectUri,
resource: params.resource,
scopes: params.scopes,
codeChallenge: params.codeChallenge,
codeChallengeMethod: "S256",
expiresAt: new Date(Date.now() + AUTH_CODE_TTL_MS),
},
})
return code
}
function ErrorCard({ title, detail }: { title: string; detail: string }) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<CardTitle className="text-xl">{title}</CardTitle>
<CardDescription>{detail}</CardDescription>
</CardHeader>
<CardContent>
<p className="text-center text-sm text-muted-foreground">
Nothing was connected. Try starting the connection again from the app
you were using.
</p>
</CardContent>
</Card>
</div>
)
}

View File

@@ -0,0 +1,71 @@
"use client"
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Loader2 } from "lucide-react"
/**
* Approve or deny.
*
* The endpoint answers with JSON containing the URL to go to, and the browser
* navigates itself, rather than the POST replying with a 302 to claude.ai. The
* CSP sets `form-action 'self'`, and browsers have historically disagreed about
* whether that also constrains the redirect a form submission lands on. A
* client-side navigation sidesteps the question and gives somewhere to show an
* error if the request fails.
*/
export function ConsentForm({ search }: { search: string }) {
const [busy, setBusy] = useState<"allow" | "deny" | null>(null)
const [error, setError] = useState("")
async function decide(decision: "allow" | "deny") {
setBusy(decision)
setError("")
try {
const res = await fetch("/api/oauth/authorize", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ decision, search }),
})
const body = await res.json()
if (!res.ok || !body.redirectTo) {
setError(body.error_description ?? body.error ?? "Something went wrong.")
setBusy(null)
return
}
window.location.assign(body.redirectTo)
} catch {
setError("Could not reach the server. Please try again.")
setBusy(null)
}
}
return (
<div className="space-y-3">
{error && (
<div className="rounded-md bg-destructive/10 p-3 text-sm text-destructive">
{error}
</div>
)}
<div className="flex gap-3">
<Button
variant="outline"
className="flex-1"
disabled={busy !== null}
onClick={() => decide("deny")}
>
{busy === "deny" && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Deny
</Button>
<Button
className="flex-1"
disabled={busy !== null}
onClick={() => decide("allow")}
>
{busy === "allow" && <Loader2 className="mr-2 h-4 w-4 animate-spin" />}
Allow
</Button>
</div>
</div>
)
}

View File

@@ -0,0 +1,394 @@
"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 { Separator } from "@/components/ui/separator"
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
}
interface McpGrant {
id: string
clientName: string
clientUri: string | null
scopes: string[]
createdAt: string
lastUsedAt: string | null
}
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<CreatedToken | null>(null)
const [copied, setCopied] = useState<string | null>(null)
const { data, isLoading } = useQuery<TokensResponse>({
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"] })
},
})
// Apps connected through OAuth rather than a pasted token: claude.ai and
// ChatGPT arrive this way.
const { data: grantData } = useQuery<{ grants: McpGrant[] }>({
queryKey: ["mcp-grants"],
queryFn: async () => {
const res = await fetch("/api/settings/mcp-grants")
if (!res.ok) throw new Error("Failed to load connected apps")
return res.json()
},
})
const disconnect = useMutation({
mutationFn: async (id: string) => {
const res = await fetch(`/api/settings/mcp-grants/${id}`, {
method: "DELETE",
})
if (!res.ok) throw new Error("Failed to disconnect")
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["mcp-grants"] })
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 (
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Plug className="h-5 w-5" />
AI assistant access
</CardTitle>
<CardDescription>
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.
</CardDescription>
</CardHeader>
<CardContent className="space-y-6">
{created && (
<div className="rounded-lg border border-amber-500/50 bg-amber-500/5 p-4 space-y-3">
<div className="flex items-start justify-between gap-2">
<div>
<p className="font-medium">Your new token</p>
<p className="text-sm text-muted-foreground">
Copy it now. It is stored only as a hash, so it cannot be shown
again.
</p>
</div>
<Button
variant="ghost"
size="sm"
onClick={() => setCreated(null)}
aria-label="Dismiss"
>
Done
</Button>
</div>
<div className="flex gap-2">
<code className="flex-1 overflow-x-auto rounded bg-muted px-3 py-2 text-xs">
{created.secret}
</code>
<Button
variant="outline"
size="sm"
onClick={() => copy("secret", created.secret)}
>
{copied === "secret" ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
<div className="space-y-1">
<p className="text-sm font-medium">Connect Claude Code</p>
<div className="flex gap-2">
<code className="flex-1 overflow-x-auto whitespace-pre rounded bg-muted px-3 py-2 text-xs">
{connectCommand}
</code>
<Button
variant="outline"
size="sm"
onClick={() => copy("cmd", connectCommand)}
>
{copied === "cmd" ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
</Button>
</div>
</div>
</div>
)}
{!!grantData?.grants.length && (
<div className="space-y-2">
<p className="text-sm font-medium">Connected apps</p>
{grantData.grants.map((grant) => (
<div
key={grant.id}
className="flex items-center justify-between gap-3 rounded-lg border p-3"
>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">{grant.clientName}</span>
<Badge variant="secondary">
{grant.scopes.some((s) => s.endsWith(":write"))
? "read/write"
: "read only"}
</Badge>
</div>
<p className="mt-1 text-xs text-muted-foreground">
Connected {new Date(grant.createdAt).toLocaleDateString()}
{grant.lastUsedAt
? ` · last used ${new Date(grant.lastUsedAt).toLocaleDateString()}`
: ""}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => disconnect.mutate(grant.id)}
disabled={disconnect.isPending}
>
<Trash2 className="mr-1 h-4 w-4" />
Disconnect
</Button>
</div>
))}
<Separator className="!mt-4" />
</div>
)}
<p className="text-sm font-medium">
Access tokens
<span className="ml-2 font-normal text-muted-foreground">
for clients you configure by hand, such as Claude Code
</span>
</p>
<div className="grid gap-3 sm:grid-cols-3">
<div className="space-y-1.5">
<Label htmlFor="mcp-name">Name</Label>
<Input
id="mcp-name"
placeholder="Laptop"
value={name}
maxLength={100}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div className="space-y-1.5">
<Label htmlFor="mcp-access">Access</Label>
<Select
id="mcp-access"
value={access}
onChange={(e) => setAccess(e.target.value)}
>
{ACCESS_OPTIONS.map((o) => (
<SelectOption key={o.value} value={o.value}>
{o.label}
</SelectOption>
))}
</Select>
</div>
<div className="space-y-1.5">
<Label htmlFor="mcp-expiry">Expires</Label>
<Select
id="mcp-expiry"
value={expiry}
onChange={(e) => setExpiry(e.target.value)}
>
{EXPIRY_OPTIONS.map((o) => (
<SelectOption key={o.value} value={o.value}>
{o.label}
</SelectOption>
))}
</Select>
</div>
</div>
<div className="flex items-center gap-3">
<Button onClick={() => create.mutate()} disabled={create.isPending}>
{create.isPending && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
Create token
</Button>
{create.isError && (
<p className="text-sm text-destructive">
{(create.error as Error).message}
</p>
)}
</div>
<div className="space-y-2">
{isLoading && (
<p className="text-sm text-muted-foreground">Loading</p>
)}
{!isLoading && !data?.tokens.length && (
<p className="text-sm text-muted-foreground">
No tokens yet. Create one to connect an assistant.
</p>
)}
{data?.tokens.map((token) => (
<div
key={token.id}
className="flex items-center justify-between gap-3 rounded-lg border p-3"
>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<span className="font-medium">
{token.name ?? "Unnamed token"}
</span>
<code className="text-xs text-muted-foreground">
dtk_{token.prefix}
</code>
<Badge variant="secondary">
{token.scopes.some((s) => s.endsWith(":write"))
? "read/write"
: "read only"}
</Badge>
<ExpiryBadge expiresAt={token.expiresAt} />
</div>
<p className="mt-1 text-xs text-muted-foreground">
{token.lastUsedAt
? `Last used ${new Date(token.lastUsedAt).toLocaleDateString()}`
: "Never used"}
</p>
</div>
<Button
variant="outline"
size="sm"
onClick={() => revoke.mutate(token.id)}
disabled={revoke.isPending}
>
<Trash2 className="mr-1 h-4 w-4" />
Revoke
</Button>
</div>
))}
</div>
{serverUrl && (
<p className="text-xs text-muted-foreground">
Server URL: <code>{serverUrl}</code>
</p>
)}
</CardContent>
</Card>
)
}
function ExpiryBadge({ expiresAt }: { expiresAt: string | null }) {
if (!expiresAt) return <Badge variant="outline">no expiry</Badge>
const days = Math.ceil(
(new Date(expiresAt).getTime() - Date.now()) / (24 * 60 * 60 * 1000)
)
if (days <= 0) return <Badge variant="destructive">expired</Badge>
// Flagged early enough to rotate before a client starts failing.
if (days <= 14) return <Badge variant="destructive">{days}d left</Badge>
return <Badge variant="outline">{days}d left</Badge>
}

View File

@@ -11,6 +11,7 @@ import { Badge } from "@/components/ui/badge"
import { Separator } from "@/components/ui/separator" import { Separator } from "@/components/ui/separator"
import { Key, Trash2, Check, Loader2, Shield, Sliders } from "lucide-react" import { Key, Trash2, Check, Loader2, Shield, Sliders } from "lucide-react"
import { BackupRestore } from "@/components/settings/backup-restore" import { BackupRestore } from "@/components/settings/backup-restore"
import { McpTokensCard } from "@/components/settings/mcp-tokens-card"
import { DeleteAccountCard } from "@/components/settings/delete-account-card" import { DeleteAccountCard } from "@/components/settings/delete-account-card"
interface ApiKeyInfo { interface ApiKeyInfo {
@@ -140,6 +141,10 @@ export function SettingsClient({ isOwner }: { isOwner: boolean }) {
</CardContent> </CardContent>
</Card> </Card>
{/* Available to every member: an MCP token only ever reaches its own
user's rows, and unlike the gateway key it spends nothing. */}
<McpTokensCard />
{/* Backup & Restore Section */} {/* Backup & Restore Section */}
<BackupRestore /> <BackupRestore />

View File

@@ -16,6 +16,17 @@ const PUBLIC_ROUTES = [
"/invite", "/invite",
"/reset", "/reset",
"/share", "/share",
// OAuth discovery documents for the MCP server. These have to be readable
// without a session - an MCP client fetches them before it has any
// credential, and `authorized` would otherwise answer with an HTML redirect
// to /login, which the client cannot parse and reports as "couldn't reach
// the server". Being a prefix match, this makes any future /.well-known/*
// route public too, so put nothing there that isn't meant to be.
//
// Note /oauth/authorize is deliberately NOT here: the consent screen must
// sit behind the session, and the redirect to /login is exactly what should
// happen when a client sends an unauthenticated user to it.
"/.well-known",
] ]
// Email and password only. Google and GitHub were configured but never had // Email and password only. Google and GitHub were configured but never had

46
src/lib/mcp/audit.ts Normal file
View File

@@ -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))
}

99
src/lib/mcp/auth.ts Normal file
View File

@@ -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<AuthInfo | undefined> {
// 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))
}

View File

@@ -0,0 +1,139 @@
import { prisma } from "@/lib/prisma"
import { mcpResourceUrl } from "@/lib/mcp/config"
import { findMatchingRedirectUri, parseScopes } from "@/lib/mcp/oauth"
/**
* Validation for an /oauth/authorize request, shared by the consent page and the
* approve endpoint so the two cannot drift.
*
* Order matters and is the whole point of the two-stage result below. Until the
* client and its redirect URI are known good there is nowhere safe to send an
* error, because an unvalidated redirect_uri is an open redirect. Only after
* both check out do errors become redirects, as RFC 6749 requires.
*/
export interface AuthorizeParams {
clientId: string
redirectUri: string
state: string | null
scopes: string[]
codeChallenge: string
resource: string | null
}
export interface ResolvedClient {
id: string
clientId: string
clientName: string
clientUri: string | null
}
export type AuthorizeValidation =
/** Nothing may be redirected. Render this on our own page. */
| { kind: "fatal"; message: string }
/** Client and redirect are trustworthy; report this back to the client. */
| {
kind: "redirectable"
error: string
description: string
redirectUri: string
state: string | null
}
| { kind: "ok"; params: AuthorizeParams; client: ResolvedClient }
export async function validateAuthorizeRequest(
search: URLSearchParams
): Promise<AuthorizeValidation> {
const clientId = search.get("client_id")
const redirectUri = search.get("redirect_uri")
if (!clientId) return { kind: "fatal", message: "Missing client_id." }
if (!redirectUri) return { kind: "fatal", message: "Missing redirect_uri." }
const client = await prisma.oAuthClient.findUnique({
where: { clientId },
select: {
id: true,
clientId: true,
clientName: true,
clientUri: true,
redirectUris: true,
},
})
if (!client) return { kind: "fatal", message: "Unknown client_id." }
// Port-agnostic for loopback, exact otherwise. Returns the registered form.
const matched = findMatchingRedirectUri(client.redirectUris, redirectUri)
if (!matched) {
return {
kind: "fatal",
message: "The redirect_uri does not match any registered for this client.",
}
}
// From here on the redirect target is trusted, so problems go back to it.
const state = search.get("state")
const fail = (error: string, description: string): AuthorizeValidation => ({
kind: "redirectable",
error,
description,
redirectUri,
state,
})
if (search.get("response_type") !== "code") {
return fail("unsupported_response_type", "Only response_type=code is supported.")
}
const codeChallenge = search.get("code_challenge")
if (!codeChallenge) {
return fail("invalid_request", "PKCE is required: code_challenge is missing.")
}
const method = search.get("code_challenge_method")
if (method !== "S256") {
return fail(
"invalid_request",
"code_challenge_method must be S256; plain is not accepted."
)
}
// RFC 8707. If a client names an audience it must be this MCP server, or a
// token minted here could be replayed somewhere it was never meant for.
const resource = search.get("resource")
if (resource && resource.replace(/\/$/, "") !== mcpResourceUrl()) {
return fail(
"invalid_target",
`Unknown resource. This server issues tokens for ${mcpResourceUrl()}.`
)
}
return {
kind: "ok",
params: {
clientId,
redirectUri,
state,
scopes: parseScopes(search.get("scope")),
codeChallenge,
resource: resource ?? null,
},
client: {
id: client.id,
clientId: client.clientId,
clientName: client.clientName,
clientUri: client.clientUri,
},
}
}
/** Builds the URL to send the user back to, preserving `state`. */
export function buildRedirect(
redirectUri: string,
params: Record<string, string | null>
): string {
const url = new URL(redirectUri)
for (const [key, value] of Object.entries(params)) {
if (value !== null) url.searchParams.set(key, value)
}
return url.toString()
}

61
src/lib/mcp/config.ts Normal file
View File

@@ -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}`
}

55
src/lib/mcp/context.ts Normal file
View File

@@ -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"
)
}

118
src/lib/mcp/define.ts Normal file
View File

@@ -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<S extends z.ZodTypeAny> {
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<S extends z.ZodTypeAny> = (
args: z.infer<S>,
caller: McpCaller
) => Promise<CallToolResult | ToolOutcome>
/**
* 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<S extends z.ZodTypeAny>(
server: McpServer,
spec: ToolSpec<S>,
handler: ToolHandler<S>
): 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<S>, 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
)
}

276
src/lib/mcp/oauth.ts Normal file
View File

@@ -0,0 +1,276 @@
import { createHash, randomBytes, timingSafeEqual } from "crypto"
import { NextResponse } from "next/server"
import { prisma } from "@/lib/prisma"
import { generateMcpToken } from "@/lib/mcp/tokens"
import { MCP_SCOPES, type McpScope } from "@/lib/mcp/config"
/**
* OAuth 2.1 authorization server primitives.
*
* This app is both the authorization server and the resource server, and it
* serves public clients only - no client secrets are stored anywhere, so there
* is nothing here to leak. Clients authenticate at the token endpoint with PKCE,
* which Claude always sends with S256.
*/
/** Access tokens are short; the refresh token is what carries the session. */
export const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000
export const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000
/** Long enough for a redirect and a token call, short enough to be useless if leaked. */
export const AUTH_CODE_TTL_MS = 60 * 1000
export const OFFLINE_ACCESS = "offline_access"
/** Advertised in discovery metadata and offered on the consent screen. */
export const SUPPORTED_SCOPES: string[] = [...MCP_SCOPES, OFFLINE_ACCESS]
export const SCOPE_DESCRIPTIONS: Record<string, string> = {
"drinks:read": "See your drinks, ratings, wishlist and taste preferences",
"drinks:write": "Add, edit and delete drinks, ratings and wishlist entries",
"bar:read": "See your bar inventory and saved recipes",
"bar:write": "Add, edit and delete bar items and recipes",
[OFFLINE_ACCESS]: "Stay connected without asking you to sign in again",
}
// ─── Opaque secrets ──────────────────────────────────────────────
export function sha256(value: string): string {
return createHash("sha256").update(value).digest("hex")
}
export function generateAuthCode(): { code: string; hash: string } {
const code = randomBytes(32).toString("base64url")
return { code, hash: sha256(code) }
}
export function generateRefreshToken(): { token: string; hash: string } {
const token = randomBytes(32).toString("base64url")
return { token, hash: sha256(token) }
}
export function generateClientId(): string {
return `dtc_${randomBytes(16).toString("hex")}`
}
// ─── Scopes ──────────────────────────────────────────────────────
/**
* Narrow a requested scope string to what this server actually grants. Unknown
* scopes are dropped rather than rejected: an unrecognised scope is not an error
* per RFC 6749, and rejecting would break clients that request extras.
*/
export function parseScopes(requested: string | null | undefined): string[] {
const asked = (requested ?? "").split(/\s+/).filter(Boolean)
const granted = asked.filter((s) => SUPPORTED_SCOPES.includes(s))
// Default to read-only when nothing usable was asked for.
if (granted.filter((s) => s !== OFFLINE_ACCESS).length === 0) {
return ["drinks:read", "bar:read", ...granted.filter((s) => s === OFFLINE_ACCESS)]
}
return granted
}
/** The scopes actually stored on an access token: everything except the marker. */
export function accessScopes(scopes: string[]): McpScope[] {
return scopes.filter((s): s is McpScope =>
(MCP_SCOPES as readonly string[]).includes(s)
)
}
export function coversScopes(granted: string[], requested: string[]): boolean {
return requested.every((s) => granted.includes(s))
}
// ─── PKCE ────────────────────────────────────────────────────────
/** RFC 7636 unreserved set, 43-128 characters. */
const VERIFIER_RE = /^[A-Za-z0-9\-._~]{43,128}$/
export function verifyPkce(verifier: string, challenge: string): boolean {
if (!VERIFIER_RE.test(verifier)) return false
const computed = createHash("sha256").update(verifier).digest("base64url")
const a = Buffer.from(computed)
const b = Buffer.from(challenge)
// Length check first: timingSafeEqual throws on a mismatch rather than
// returning false.
if (a.length !== b.length) return false
return timingSafeEqual(a, b)
}
// ─── Redirect URIs ───────────────────────────────────────────────
function isLoopback(url: URL): boolean {
return (
url.protocol === "http:" &&
(url.hostname === "localhost" ||
url.hostname === "127.0.0.1" ||
url.hostname === "[::1]" ||
url.hostname === "::1")
)
}
/**
* A redirect URI is acceptable at registration if it is https, or an RFC 8252
* loopback address. Fragments are forbidden by RFC 6749.
*/
export function isRegisterableRedirectUri(value: string): boolean {
let url: URL
try {
url = new URL(value)
} catch {
return false
}
if (url.hash) return false
return url.protocol === "https:" || isLoopback(url)
}
/**
* Matching a redirect at authorize time.
*
* Exact string equality, except for loopback addresses where the port is
* ignored. This is the single most common cause of a silently broken native
* client: Claude Code registers http://localhost/callback and
* http://127.0.0.1/callback, then redirects to an ephemeral port such as
* http://localhost:51234/callback. RFC 8252 section 7.3 requires the port to be
* ignored for the IP-literal form; the same is applied to localhost so Claude
* Code works at all.
*/
export function redirectUriMatches(registered: string, requested: string): boolean {
if (registered === requested) return true
let a: URL, b: URL
try {
a = new URL(registered)
b = new URL(requested)
} catch {
return false
}
if (!isLoopback(a) || !isLoopback(b)) return false
return (
a.protocol === b.protocol &&
a.hostname === b.hostname &&
a.pathname === b.pathname
)
}
export function findMatchingRedirectUri(
registered: string[],
requested: string
): string | null {
return registered.find((uri) => redirectUriMatches(uri, requested)) ?? null
}
// ─── Errors ──────────────────────────────────────────────────────
/**
* RFC 6749 error body. `invalid_grant` in particular is load-bearing: Claude
* keys off exactly that code to decide a refresh token is dead and it should
* restart the whole flow. Any other code leaves the connection stuck.
*/
export function oauthError(
error: string,
description?: string,
status = 400
): NextResponse {
return NextResponse.json(
{ error, ...(description ? { error_description: description } : {}) },
{ status, headers: { "Cache-Control": "no-store", Pragma: "no-cache" } }
)
}
// ─── Token issuance ──────────────────────────────────────────────
export interface IssuedTokens {
access_token: string
token_type: "Bearer"
expires_in: number
scope: string
refresh_token?: string
}
/**
* Mints an access token against a grant.
*
* Refresh tokens are deliberately NOT handled here. The two call sites need
* different behaviour - the code exchange creates the first one, a refresh
* rotates the existing one and has to record the previous hash for replay
* detection - and doing it in here once meant the rotation was silently
* overwritten and the token handed back matched nothing on file.
*
* The access token is an ordinary McpAccessToken row with source "oauth", the
* same shape a hand-minted one has, so verifyMcpToken needs no OAuth awareness.
* Previously outstanding tokens on the grant are revoked, so a refresh replaces
* rather than accumulates.
*/
export async function issueAccessToken(
grantId: string,
userId: string,
scopes: string[],
clientName: string
): Promise<IssuedTokens> {
const access = generateMcpToken()
await prisma.$transaction(async (tx) => {
await tx.mcpAccessToken.updateMany({
where: { grantId, revokedAt: null },
data: { revokedAt: new Date() },
})
await tx.mcpAccessToken.create({
data: {
userId,
tokenHash: access.hash,
prefix: access.prefix,
name: clientName,
scopes: accessScopes(scopes),
source: "oauth",
grantId,
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
},
})
await tx.oAuthGrant.update({
where: { id: grantId },
data: { scopes, lastUsedAt: new Date() },
})
})
return {
access_token: access.raw,
token_type: "Bearer",
expires_in: Math.floor(ACCESS_TOKEN_TTL_MS / 1000),
scope: scopes.join(" "),
}
}
/** Stores a freshly minted refresh token on the grant, keeping the old hash for replay detection. */
export async function storeRefreshToken(
grantId: string,
hash: string,
previousHash: string | null
): Promise<void> {
await prisma.oAuthGrant.update({
where: { id: grantId },
data: {
refreshHash: hash,
refreshPrevHash: previousHash,
refreshExpiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
},
})
}
/** Kills a grant and every access token it issued. */
export async function revokeGrant(grantId: string): Promise<void> {
const now = new Date()
await prisma.$transaction([
prisma.mcpAccessToken.updateMany({
where: { grantId, revokedAt: null },
data: { revokedAt: now },
}),
prisma.oAuthGrant.update({
where: { id: grantId },
data: {
revokedAt: now,
refreshHash: null,
refreshPrevHash: null,
},
}),
])
}

160
src/lib/mcp/render.ts Normal file
View File

@@ -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<string, unknown>
): 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])}`
}

147
src/lib/mcp/schemas.ts Normal file
View File

@@ -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 <img> 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,
})

38
src/lib/mcp/server.ts Normal file
View File

@@ -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)
}
}

50
src/lib/mcp/tokens.ts Normal file
View File

@@ -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)
}

118
src/lib/mcp/tools/bar.ts Normal file
View File

@@ -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,
}
}
)
}

View File

@@ -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,
},
})
}
)
}

445
src/lib/mcp/tools/drinks.ts Normal file
View File

@@ -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,
})),
})
}
)
}

73
src/lib/mcp/tools/meta.ts Normal file
View File

@@ -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,
})
}
)
}

View File

@@ -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,
}
}
)
}

View File

@@ -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,
}
}
)
}